// Package podapi answers the pods that ask lanyard for credentials. // // GET /v1/github/{owner}/{repo} // GET /v1/gitea/{account} // GET /v1/atproto/{account}/service?aud={did}&lxm={nsid} // GET /v1/atproto/{account}/session // GET /v1/secrets/{badge}/{name} // GET /v1/lanyard // // A pod sends its ServiceAccount token as a bearer token. What it may // have comes from the Badges of its namespace that name its // ServiceAccount, read from the API server on each request. package podapi import ( "context" "crypto/rsa" "encoding/json" "errors" "fmt" "log/slog" "net/http" "regexp" "slices" "strconv" "strings" "time" "github.com/prometheus/client_golang/prometheus" "tangled.org/guid.foo/lanyard/api/v1alpha1" "tangled.org/guid.foo/lanyard/atproto" "tangled.org/guid.foo/lanyard/badge" "tangled.org/guid.foo/lanyard/cluster" "tangled.org/guid.foo/lanyard/gitea" "tangled.org/guid.foo/lanyard/github" "tangled.org/guid.foo/lanyard/metrics" ) // Issuers are the token caches the routes answer from. type Issuers struct { GitHub *github.Tokens Gitea *gitea.Tokens Atproto *atproto.Tokens } // Server answers the API. type Server struct { // namespace is lanyard's own, where each App's private key, each // Gitea account's password, and each atproto account's app password // is. namespace string cluster *cluster.Cluster tokens *github.Tokens gitea *gitea.Tokens atproto *atproto.Tokens log *slog.Logger metrics *metrics.Metrics requests *prometheus.CounterVec } // The routes, as lanyard_requests_total names them. const ( routeGitHub = "github" routeGitea = "gitea" routeAtprotoService = "atproto_service" routeAtprotoSession = "atproto_session" routeSecrets = "secrets" routeLanyard = "lanyard" ) // The reasons of lanyard_requests_total. An answer of 200 has none. const ( // reasonUnauthenticated: the request had no token, or the API // server did not accept it. reasonUnauthenticated = "unauthenticated" // reasonPod: the token's pod is gone, has finished, is another pod // of its name, or runs as another ServiceAccount. reasonPod = "pod" // reasonBadge: no Badge of the ServiceAccount allows the request. reasonBadge = "badge" // reasonName: the path names no repository or object. reasonName = "name" // reasonMissing: a GitHubApp, a GiteaAccount, an AtprotoAccount, a // key, a password, a Secret, or an installation that the request // needs does not exist. reasonMissing = "missing" // reasonFork: the repository is a fork, and no Badge allows a fork. reasonFork = "fork" // reasonPermissions: the App lacks a permission a Badge gives. reasonPermissions = "permissions" // reasonError: lanyard failed, or something it asked did, and the // log says what. reasonError = "error" ) // New answers a Server that reads App keys, Gitea passwords, and atproto // app passwords from namespace, and counts its requests and its failed tokens on m. func New(namespace string, c *cluster.Cluster, issuers Issuers, log *slog.Logger, m *metrics.Metrics) *Server { requests := prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "lanyard_requests_total", Help: "Requests from pods, by route, by the status lanyard answered, and by the reason of an answer other than 200.", }, []string{"route", "code", "reason"}) m.Registry.MustRegister(requests) // An alert divides a route's failures by its requests, and a // counter that appears only at its first increase hides that // increase from rate(), so both start at zero. for _, route := range []string{routeGitHub, routeGitea, routeAtprotoService, routeAtprotoSession, routeSecrets, routeLanyard} { requests.WithLabelValues(route, strconv.Itoa(http.StatusOK), "") requests.WithLabelValues(route, strconv.Itoa(http.StatusInternalServerError), reasonError) } return &Server{namespace: namespace, cluster: c, tokens: issuers.GitHub, gitea: issuers.Gitea, atproto: issuers.Atproto, log: log, metrics: m, requests: requests} } // Handler answers the API's routes. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /v1/github/{owner}/{repo}", s.route(routeGitHub, s.github)) mux.HandleFunc("GET /v1/gitea/{account}", s.route(routeGitea, s.giteaToken)) mux.HandleFunc("GET /v1/atproto/{account}/service", s.route(routeAtprotoService, s.atprotoService)) mux.HandleFunc("GET /v1/atproto/{account}/session", s.route(routeAtprotoSession, s.atprotoSession)) mux.HandleFunc("GET /v1/secrets/{badge}/{name}", s.route(routeSecrets, s.secret)) mux.HandleFunc("GET /v1/lanyard", s.route(routeLanyard, s.lanyard)) return mux } // asker is the pod that sent a request, and the Badges it holds. type asker struct { cluster.Caller badges []v1alpha1.Badge } // refusal is an answer other than the thing asked for. Its reason goes // to the caller, so it names nothing but the caller's own request and // Badges. Its kind is the reason of lanyard_requests_total, one of a // few, because the reason itself names objects. type refusal struct { status int kind string reason string } func (r refusal) Error() string { return r.reason } func refuse(status int, kind, format string, args ...any) error { return refusal{status: status, kind: kind, reason: fmt.Sprintf(format, args...)} } // route identifies the caller, runs one route, and writes its answer or // its refusal. No answer may be stored by anything between lanyard and // the pod. func (s *Server) route(name string, answer func(context.Context, *http.Request, asker) (any, error)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") status, kind := http.StatusOK, "" who, err := s.identify(r.Context(), r) var body any if err == nil { body, err = answer(r.Context(), r, who) } if err != nil { status, kind = s.refused(w, r, who, err) } else { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(body) } s.requests.WithLabelValues(name, strconv.Itoa(status), kind).Inc() } } // identify answers the pod that a request's token belongs to, with the // Badges it holds. The token names a pod, and the pod must still be // that pod, must not have finished, and must run as the token's // ServiceAccount. func (s *Server) identify(ctx context.Context, r *http.Request) (asker, error) { token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || token == "" { return asker{}, cluster.ErrUnauthenticated } caller, err := s.cluster.Review(ctx, token) if err != nil { return asker{}, err } who := asker{Caller: caller} pod, err := s.cluster.Pod(ctx, caller.Namespace, caller.Pod) if errors.Is(err, cluster.ErrNotFound) { return who, refuse(http.StatusForbidden, reasonPod, "the pod %s is gone", caller.Pod) } if err != nil { return who, err } switch { case pod.UID != caller.PodUID: return who, refuse(http.StatusForbidden, reasonPod, "the pod %s is another pod of the same name", caller.Pod) case pod.Finished(): return who, refuse(http.StatusForbidden, reasonPod, "the pod %s has finished", caller.Pod) case pod.ServiceAccount != caller.ServiceAccount: return who, refuse(http.StatusForbidden, reasonPod, "the token's ServiceAccount is not the pod's") } badges, err := s.cluster.Badges(ctx, caller.Namespace) if err != nil { return who, err } who.badges = badge.Held(badges, caller.ServiceAccount) return who, nil } // refused writes the status of an error, and answers it with the // error's kind. A refusal says its reason. Any other failure says only // its status, and the log has the rest. func (s *Server) refused(w http.ResponseWriter, r *http.Request, who asker, err error) (int, string) { status, kind, reason := http.StatusInternalServerError, reasonError, "" var refused refusal switch { case errors.Is(err, cluster.ErrUnauthenticated): status, kind = http.StatusUnauthorized, reasonUnauthenticated case errors.As(err, &refused): status, kind, reason = refused.status, refused.kind, refused.reason } if reason == "" { reason = http.StatusText(status) } log := s.log.Warn if status >= http.StatusInternalServerError { log = s.log.Error } log("refused a request", "path", r.URL.Path, "status", status, "namespace", who.Namespace, "pod", who.Pod, "serviceAccount", who.ServiceAccount, "reason", err.Error()) http.Error(w, reason, status) return status, kind } var ( ownerPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$`) repositoryPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`) ) // Token is a GitHub token as a pod receives it. type Token struct { Token string `json:"token"` ExpiresAt time.Time `json:"expiresAt"` } func (s *Server) github(ctx context.Context, r *http.Request, who asker) (any, error) { owner, repository := r.PathValue("owner"), r.PathValue("repo") if !ownerPattern.MatchString(owner) || !repositoryPattern.MatchString(repository) || strings.Trim(repository, ".") == "" { return nil, refuse(http.StatusBadRequest, reasonName, "%s/%s is not the name of a repository", owner, repository) } allowed, found := badge.ForOwner(who.badges, owner) if !found { return nil, refuse(http.StatusForbidden, reasonBadge, "no Badge of the ServiceAccount %s names the owner %s", who.ServiceAccount, owner) } app, err := s.cluster.GitHubApp(ctx, v1alpha1.GitHubAppName(owner)) if errors.Is(err, cluster.ErrNotFound) { return nil, refuse(http.StatusNotFound, reasonMissing, "there is no GitHubApp for the owner %s", owner) } if err != nil { return nil, err } token, err := s.tokens.Get(ctx, github.Request{ ClientID: app.Spec.ClientID, Key: func() (*rsa.PrivateKey, error) { return s.key(ctx, app) }, Owner: owner, Repository: repository, Permissions: allowed.Permissions, ForkPermissions: allowed.ForkPermissions, }) // The App's name is its owner in lower case, and comes from an // object a person made, so the series stay few whatever a pod asks. if reason := githubFailure(err); reason != "" { s.metrics.GitHubTokenFailed(app.Metadata.Name, reason) } switch { case errors.Is(err, errNoKey): return nil, refuse(http.StatusNotFound, reasonMissing, "the GitHubApp for %s has no private key in lanyard's namespace", owner) case errors.Is(err, github.ErrFork): return nil, refuse(http.StatusForbidden, reasonFork, "%s/%s is a fork, and no Badge of the ServiceAccount %s gives a token for a fork", owner, repository, who.ServiceAccount) case errors.Is(err, github.ErrNotInstalled): return nil, refuse(http.StatusNotFound, reasonMissing, "the GitHub App for %s is not installed on %s/%s, or there is no such repository", owner, owner, repository) case errors.Is(err, github.ErrPermissions): s.log.Error("the App lacks a permission that Badges give", "owner", owner, "namespace", who.Namespace, "serviceAccount", who.ServiceAccount, "error", err) return nil, refuse(http.StatusForbidden, reasonPermissions, "the GitHub App for %s does not hold every permission that the Badges of the ServiceAccount %s give", owner, who.ServiceAccount) case err != nil: return nil, err } s.log.Info("gave a GitHub token", "namespace", who.Namespace, "pod", who.Pod, "serviceAccount", who.ServiceAccount, "repository", owner+"/"+repository, "permissions", allowed.Permissions, "expiresAt", token.ExpiresAt) return Token{Token: token.Value, ExpiresAt: token.ExpiresAt}, nil } // githubFailure answers the reason of lanyard_github_token_errors_total // for an error of a request for a token, or nothing for a success and // for a fork, which is a refusal of the pod and no fault of the App. func githubFailure(err error) string { switch { case err == nil, errors.Is(err, github.ErrFork): return "" case errors.Is(err, errNoKey): return metrics.GitHubNoKey case errors.Is(err, github.ErrRefused), errors.Is(err, github.ErrUnknownApp): return metrics.GitHubRefused case errors.Is(err, github.ErrNotInstalled): return metrics.GitHubNotInstalled case errors.Is(err, github.ErrPermissions): return metrics.GitHubPermissions } return metrics.GitHubFailed } // errNoKey means the Secret of a GitHubApp's private key, or its key, // does not exist. var errNoKey = errors.New("the GitHubApp's private key does not exist") // key reads an App's private key from its Secret in lanyard's namespace. func (s *Server) key(ctx context.Context, app *v1alpha1.GitHubApp) (*rsa.PrivateKey, error) { ref := app.Spec.PrivateKey.SecretKeyRef data, err := s.cluster.Secret(ctx, s.namespace, ref.Name) if errors.Is(err, cluster.ErrNotFound) { return nil, fmt.Errorf("%w: there is no Secret %s", errNoKey, ref.Name) } if err != nil { return nil, fmt.Errorf("reading the key of the GitHubApp %s: %w", app.Metadata.Name, err) } pem, ok := data[ref.Key] if !ok { return nil, fmt.Errorf("%w: the Secret %s has no key %s", errNoKey, ref.Name, ref.Key) } key, err := github.ParseKey(pem) if err != nil { return nil, fmt.Errorf("the key of the GitHubApp %s: %w", app.Metadata.Name, err) } return key, nil } // Secret is a Secret's keys as a pod receives them. Each value is in // base64, as the API server holds it. type Secret struct { Data map[string][]byte `json:"data"` } func (s *Server) secret(ctx context.Context, r *http.Request, who asker) (any, error) { held, name := r.PathValue("badge"), r.PathValue("name") secret, found := badge.Secret(who.badges, held, name) if !found { return nil, refuse(http.StatusForbidden, reasonBadge, "the ServiceAccount %s holds no secret %s/%s", who.ServiceAccount, held, name) } data, err := s.cluster.Secret(ctx, who.Namespace, secret) if errors.Is(err, cluster.ErrNotFound) { return nil, refuse(http.StatusNotFound, reasonMissing, "the Secret that %s/%s refers to does not exist", held, name) } if err != nil { return nil, err } s.log.Info("gave a secret", "namespace", who.Namespace, "pod", who.Pod, "serviceAccount", who.ServiceAccount, "secret", held+"/"+name) return Secret{Data: data}, nil } // Lanyard is everything a ServiceAccount's Badges add up to, with no // values. type Lanyard struct { Namespace string `json:"namespace"` ServiceAccount string `json:"serviceAccount"` Badges []LanyardItem `json:"badges"` // GiteaAccounts are the accounts that the Badges' Gitea entries // name and that have a GiteaAccount, so a client can match a git // host to an account. GiteaAccounts []GiteaAccount `json:"giteaAccounts,omitempty"` // AtprotoAccounts are the accounts that the Badges' atproto entries // name and that have an AtprotoAccount. AtprotoAccounts []AtprotoAccount `json:"atprotoAccounts,omitempty"` } // LanyardItem is one Badge on a lanyard. type LanyardItem struct { Name string `json:"name"` GitHub []v1alpha1.GitHubEntry `json:"github,omitempty"` Gitea []v1alpha1.GiteaEntry `json:"gitea,omitempty"` // Atproto are the Badge's atproto entries. Atproto []v1alpha1.AtprotoEntry `json:"atproto,omitempty"` // Secrets are the names a pod asks for, each after the Badge's name. Secrets []string `json:"secrets,omitempty"` } // GiteaAccount is where a Gitea account's tokens work, and as whom. type GiteaAccount struct { Name string `json:"name"` URL string `json:"url"` Username string `json:"username"` } // AtprotoAccount is where an atproto account signs in, and as whom. type AtprotoAccount struct { Name string `json:"name"` PDS string `json:"pds"` Identifier string `json:"identifier"` } func (s *Server) lanyard(ctx context.Context, _ *http.Request, who asker) (any, error) { lanyard := Lanyard{Namespace: who.Namespace, ServiceAccount: who.ServiceAccount, Badges: []LanyardItem{}} var accounts, atprotoAccounts []string for _, held := range who.badges { item := LanyardItem{Name: held.Metadata.Name, GitHub: held.Spec.GitHub, Gitea: held.Spec.Gitea, Atproto: held.Spec.Atproto} for _, entry := range held.Spec.Gitea { accounts = append(accounts, entry.Accounts...) } for _, entry := range held.Spec.Atproto { atprotoAccounts = append(atprotoAccounts, entry.Accounts...) } for _, entry := range held.Spec.Secrets { item.Secrets = append(item.Secrets, entry.Name) } lanyard.Badges = append(lanyard.Badges, item) } slices.Sort(accounts) for _, name := range slices.Compact(accounts) { account, err := s.cluster.GiteaAccount(ctx, name) if errors.Is(err, cluster.ErrNotFound) { continue } if err != nil { return nil, err } lanyard.GiteaAccounts = append(lanyard.GiteaAccounts, GiteaAccount{Name: name, URL: account.Spec.URL, Username: account.Spec.Username}) } slices.Sort(atprotoAccounts) for _, name := range slices.Compact(atprotoAccounts) { account, err := s.cluster.AtprotoAccount(ctx, name) if errors.Is(err, cluster.ErrNotFound) { continue } if err != nil { return nil, err } lanyard.AtprotoAccounts = append(lanyard.AtprotoAccounts, AtprotoAccount{Name: name, PDS: account.Spec.PDS, Identifier: account.Spec.Identifier}) } return lanyard, nil }