1package xrpc
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7
8 comatproto "github.com/bluesky-social/indigo/api/atproto"
9 "github.com/bluesky-social/indigo/atproto/syntax"
10 "github.com/bluesky-social/indigo/xrpc"
11 securejoin "github.com/cyphar/filepath-securejoin"
12 "tangled.sh/tangled.sh/core/api/tangled"
13 "tangled.sh/tangled.sh/core/knotserver/git"
14 "tangled.sh/tangled.sh/core/rbac"
15)
16
17const ActorDid string = "ActorDid"
18
19func (x *Xrpc) SetDefaultBranch(w http.ResponseWriter, r *http.Request) {
20 l := x.Logger
21 fail := func(e XrpcError) {
22 l.Error("failed", "kind", e.Tag, "error", e.Message)
23 writeError(w, e, http.StatusBadRequest)
24 }
25
26 actorDid, ok := r.Context().Value(ActorDid).(syntax.DID)
27 if !ok {
28 fail(MissingActorDidError)
29 return
30 }
31
32 var data tangled.RepoSetDefaultBranch_Input
33 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
34 fail(GenericError(err))
35 return
36 }
37
38 // unfortunately we have to resolve repo-at here
39 repoAt, err := syntax.ParseATURI(data.Repo)
40 if err != nil {
41 fail(InvalidRepoError(data.Repo))
42 return
43 }
44
45 // resolve this aturi to extract the repo record
46 ident, err := x.Resolver.ResolveIdent(r.Context(), repoAt.Authority().String())
47 if err != nil || ident.Handle.IsInvalidHandle() {
48 fail(GenericError(fmt.Errorf("failed to resolve handle: %w", err)))
49 return
50 }
51
52 xrpcc := xrpc.Client{Host: ident.PDSEndpoint()}
53 resp, err := comatproto.RepoGetRecord(r.Context(), &xrpcc, "", tangled.RepoNSID, repoAt.Authority().String(), repoAt.RecordKey().String())
54 if err != nil {
55 fail(GenericError(err))
56 return
57 }
58
59 repo := resp.Value.Val.(*tangled.Repo)
60 didPath, err := securejoin.SecureJoin(actorDid.String(), repo.Name)
61 if err != nil {
62 fail(GenericError(err))
63 return
64 }
65
66 if ok, err := x.Enforcer.IsPushAllowed(actorDid.String(), rbac.ThisServer, didPath); !ok || err != nil {
67 l.Error("insufficent permissions", "did", actorDid.String())
68 writeError(w, AccessControlError(actorDid.String()), http.StatusUnauthorized)
69 return
70 }
71
72 path, _ := securejoin.SecureJoin(x.Config.Repo.ScanPath, didPath)
73 gr, err := git.PlainOpen(path)
74 if err != nil {
75 fail(InvalidRepoError(data.Repo))
76 return
77 }
78
79 err = gr.SetDefaultBranch(data.DefaultBranch)
80 if err != nil {
81 l.Error("setting default branch", "error", err.Error())
82 writeError(w, GitError(err), http.StatusInternalServerError)
83 return
84 }
85
86 w.WriteHeader(http.StatusOK)
87}