carlos / platform Public

console: link credentials through the device-code flow

Linked deployments slice 1, Task 4 (spec 2026-11-10 §5.1, §6.1).

POST /auth/cli/start takes {"purpose":"link","name":...} and echoes the
purpose; any other purpose is 400, none is today's login. The approval
page names the deployment (LD-C01..C08) and offers only accounts where
the approver holds a role that creates apps; a forged account is LD-C07.
Collecting an approved link mints, in one transaction, a kind='link'
cli_tokens row (never expiring, name = link ID) and its links row
(token hash, generation 1), then syncs the channel; the token is
delivered even when that sync fails.

syncLinkChannel is the one writer of PutLinkChannel/RevokeLinkChannel
and reads only the links row; linkSyncLoop (worker LinkSync) retries
unsynced links every 10 s. PrincipalLink resolves only for the link's
current hash on a live link, and every existing gate (cliGateRefused,
serviceBinding, the source door) refuses it as no bearer. Link tokens
are excluded from the purge, CLITokens and the person/account revokes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6f6cad3fa4f1bfd0bc0d84ef61c6738dd6a823e2 parent f7bd634
20 files changed, +1,740 −68
  • cmd/console/main.go +4 −0
  • internal/console/apicli.go +11 −0
  • internal/console/app_source.go +4 −2
  • internal/console/authcli.go +174 −15
  • internal/console/authstore.go +169 −47
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_worker_test.go +40 −0
  • internal/console/claim_workers.go +1 −0
  • internal/console/jobs.go +1 −0
  • internal/console/jobs_test.go +1 −0
  • internal/console/links_auth_test.go +759 −0
  • internal/console/links_copy.go +37 −0
  • internal/console/links_store.go +325 −0
  • internal/console/links_sync.go +133 −0
  • internal/console/server.go +7 −0
  • internal/console/store.go +4 −0
  • internal/console/store_gate.go +1 −0
  • internal/console/svcprincipal.go +30 −2
  • internal/console/templates/cli_approve.html +37 −2
  • internal/console/testdata/claim-routes.txt +1 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 8ce8d7810..808c2a025 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -858,6 +858,10 @@ func serve() {
// the label floor. Off on a host-claim console.
go srv.RunClaimWorker(context.Background(), "FleetRelabel")
go srv.RunClaimWorker(context.Background(), "ManagedFleets")
+ // The link sync (internal/console/links_sync.go): every 10 seconds,
+ // and once at start, writes the hub registry's channel for each linked
+ // deployment whose last write failed. Reads only the console database.
+ go srv.RunClaimWorker(context.Background(), "LinkSync")
addr := envOr("CONSOLE_ADDR", "127.0.0.1:8090")
ln, err := net.Listen("tcp", addr)
if err != nil {
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index e294ba2e7..78a074f3c 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -109,6 +109,10 @@ func auditActor(p Principal, acct *Account) string {
if p.Kind == PrincipalUser {
return p.Address
}
+ if p.Kind == PrincipalLink {
+ // A linked deployment, never the person who approved the link.
+ return "link:" + acct.Sqid + "/" + p.LinkID
+ }
if p.Name == "" {
// A legacy kind='app' row has no name; keep the string the audit
// trail has always written for it, so old rows and new rows about
@@ -136,7 +140,14 @@ func auditActor(p Principal, acct *Account) string {
// The third is an account deleted out from under a live binding, which is a
// 404 rather than an error for the same reason every other missing account
// is.
+//
+// Only a SERVICE principal has a binding here. A link principal is bound to
+// an account too, but to the link doors alone: it is refused here by kind,
+// so no service door can ever read it as a binding.
func (s *Server) serviceBinding(p Principal) (*Account, bool) {
+ if p.Kind != PrincipalService {
+ return nil, false
+ }
if p.AccountID == 0 || (p.Name == "" && p.App == "") {
return nil, false
}
diff --git a/internal/console/app_source.go b/internal/console/app_source.go
index 75ed04ad1..994cb319a 100644
--- a/internal/console/app_source.go
+++ b/internal/console/app_source.go
@@ -175,9 +175,11 @@ func (s *Server) sourceAdmission(next http.HandlerFunc, cli bool) http.HandlerFu
// No usable credential is the gate's own question: it answers
// 401 "not signed in" exactly as at every other CLI door. A real
// principal that is not a person (a service or app credential)
- // gets the same 404 as a stranger, before any storage read.
+ // gets the same 404 as a stranger, before any storage read. A
+ // link credential is no credential here: it falls through to
+ // the gate's 401, exactly as no bearer does.
p, ok := s.store.CLIPrincipal(bearer(r), time.Now())
- if ok && p.Kind != PrincipalUser {
+ if ok && p.Kind == PrincipalService {
http.NotFound(w, r)
return
}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index ebd35585c..3313ebc6b 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -509,8 +509,17 @@ func (s *Server) cliGateRefused(allow svcrole.Set, h http.HandlerFunc, refused f
s.cliNotSignedIn(w)
return
}
- if p.Kind == PrincipalUser {
+ // A closed switch: a kind added later fails shut. A link
+ // credential is no credential at any door this gate guards, and
+ // gets the same 401 as no bearer at all; only the link doors
+ // (their own gate) admit it.
+ switch p.Kind {
+ case PrincipalUser:
s.noteSeen(p.Address, now)
+ case PrincipalService:
+ default:
+ s.cliNotSignedIn(w)
+ return
}
if p.Kind == PrincipalService && !allow.Permits(p.Role) {
if demoOperatorPath(r.URL.Path) {
@@ -759,32 +768,71 @@ func cleanLabel(in string) string {
// terminal has no credential yet — which is why it is rate-limited per IP,
// mints nothing but a ten-minute row, and grants nothing until a signed-in
// human approves it.
+//
+// {"purpose":"link","name":"<home name>"} opens a LINK request instead: a
+// home deployment asking for a link credential (linked deployments spec
+// §5.1). Its answer echoes "purpose":"link", because a console that predates
+// links ignores the field and would start a person's login; the home side
+// refuses to go on without the echo. Any other purpose is a 400, and a
+// request without one is exactly the person's login it always was.
func (s *Server) handleCLIStart(w http.ResponseWriter, r *http.Request) {
var req struct {
- Label string `json:"label"`
+ Label string `json:"label"`
+ Purpose *string `json:"purpose"`
+ Name string `json:"name"`
}
if !readJSON(w, r, &req) {
return
}
+ link := req.Purpose != nil
+ var linkName string
+ if link {
+ if *req.Purpose != cliPurposeLink {
+ jsonError(w, http.StatusBadRequest, `purpose must be "link" or absent`)
+ return
+ }
+ // The name is shown on the approval page as the deployment's own
+ // claim, so it gets the label's printable-ASCII cleaning.
+ if linkName = cleanLabel(req.Name); linkName == "" {
+ jsonError(w, http.StatusBadRequest, "a link request needs the deployment's name")
+ return
+ }
+ // A link's answer carries the tunnel address the home dials; a
+ // console with no hub has none to give, so it takes no links.
+ if s.cfg.TunnelHost == "" {
+ jsonError(w, http.StatusBadRequest, "this console does not take links: it has no tunnel host")
+ return
+ }
+ }
ip := s.clientIP(r)
if !s.cli.start.allow(ip, time.Now()) {
jsonError(w, http.StatusTooManyRequests, "too many login attempts from here — wait a minute and try again")
return
}
- userCode, deviceCode, err := s.store.NewCLIAuth(cleanLabel(req.Label), ip, time.Now())
+ var userCode, deviceCode string
+ var err error
+ if link {
+ userCode, deviceCode, err = s.store.NewLinkAuth(linkName, cleanLabel(req.Label), ip, time.Now())
+ } else {
+ userCode, deviceCode, err = s.store.NewCLIAuth(cleanLabel(req.Label), ip, time.Now())
+ }
if err != nil {
log.Printf("console: cli auth start: %v", err)
jsonError(w, http.StatusInternalServerError, "could not start the login — try again")
return
}
- writeJSON(w, http.StatusOK, map[string]any{
+ out := map[string]any{
"user_code": userCode,
"device_code": deviceCode,
"verification_uri": s.cfg.Origin + "/auth/cli",
"verification_uri_complete": s.cfg.Origin + "/auth/cli?code=" + url.QueryEscape(userCode),
"interval": cliPollInterval,
"expires_in": int(CLIAuthTTL.Seconds()),
- })
+ }
+ if link {
+ out["purpose"] = cliPurposeLink
+ }
+ writeJSON(w, http.StatusOK, out)
}
// handleCLIPoll is the CLI's waiting room. Every answer is 200 with a status
@@ -807,19 +855,39 @@ func (s *Server) handleCLIPoll(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusTooManyRequests, "polling too fast")
return
}
- status, token, addr, err := s.store.PollCLIAuth(req.DeviceCode, time.Now())
+ res, err := s.store.pollCLIAuth(req.DeviceCode, time.Now())
if err != nil {
log.Printf("console: cli auth poll: %v", err)
jsonError(w, http.StatusInternalServerError, "could not check the login — try again")
return
}
- out := map[string]any{"status": status, "interval": cliPollInterval}
- if status == CLIAuthApproved {
- out["token"] = token
- out["address"] = addr
+ out := map[string]any{"status": res.Status, "interval": cliPollInterval}
+ switch {
+ case res.Status != CLIAuthApproved:
+ case res.Purpose == cliPurposeLink:
+ // The credential and its links row are committed. The channel is
+ // derived from that row, so the token is delivered whether or not
+ // this first sync lands: linkSyncLoop and the link doors' own sync
+ // write it from the same row. Not cut short by a client that
+ // stops waiting.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second)
+ if err := s.syncLinkChannel(ctx, res.LinkID); err != nil {
+ log.Printf("console: link %s: first channel sync: %v (linkSyncLoop retries)", res.LinkID, err)
+ }
+ cancel()
+ out["token"] = res.Token
+ out["purpose"] = cliPurposeLink
+ out["link_id"] = res.LinkID
+ out["account"] = res.AccountSqid
+ out["tunnel_url"] = "https://" + s.cfg.TunnelHost + "/register"
+ out["apps_domain"] = s.cfg.AppsDomain
+ out["console"] = s.cfg.Origin
+ default:
+ out["token"] = res.Token
+ out["address"] = res.Address
out["expires_at"] = time.Now().Add(CLITokenTTL).UTC().Format(time.RFC3339)
out["console"] = s.cfg.Origin
- go s.notifyCLIIssued(addr, token)
+ go s.notifyCLIIssued(res.Address, res.Token)
}
writeJSON(w, http.StatusOK, out)
}
@@ -914,6 +982,11 @@ type cliPage struct {
Tokens []CLIToken
Methods []methodRow
Days int
+ // LinkAccounts are the accounts the approver may link a deployment to
+ // (linkableAccounts), for a link request's picker. LinkHome and
+ // LinkAccount name the link on the approved page.
+ LinkAccounts []Account
+ LinkHome, LinkAccount string
// ServiceAccounts maps a service credential's account id to that
// account's sqid, so the read-only mirror can say WHERE a row is managed
// and link there. Built here rather than hung on CLIToken because the
@@ -944,8 +1017,35 @@ func (p cliPage) Lede() string {
return copyText("cli.lede", "label", label, "console", p.Brand)
}
-// ApprovedText sends the person back to the agent that asked.
+// Heading is the approval page's title: LD-C01 for a link request.
+func (p cliPage) Heading() string {
+ if p.Request != nil && p.Request.IsLink() {
+ return copyLD01
+ }
+ return copyText("cli.title")
+}
+
+// The link request's lines (linked deployments deck, LD-C02 to LD-C08).
+func (p cliPage) LinkLede() string { return linkCopy(copyLD02, "home", p.linkName()) }
+func (p cliPage) LinkNote() string { return copyLD03 }
+func (p cliPage) LinkPick() string { return copyLD04 }
+func (p cliPage) LinkGrant() string { return linkCopy(copyLD05, "home", p.linkName()) }
+func (p cliPage) LinkNone() string { return copyLD06 }
+func (p cliPage) LinkNotMe() string { return copyLD08 }
+
+func (p cliPage) linkName() string {
+ if p.Request == nil {
+ return ""
+ }
+ return p.Request.LinkName
+}
+
+// ApprovedText sends the person back to the agent that asked, or for a
+// link, says what the deployment can now do (LD-C09).
func (p cliPage) ApprovedText() string {
+ if p.LinkHome != "" {
+ return linkCopy(copyLD09, "home", p.LinkHome, "account", p.LinkAccount)
+ }
label := p.Label
if label == "" {
label = copyText("cli.unnamed")
@@ -1037,10 +1137,51 @@ func (s *Server) handleCLIApprovePage(w http.ResponseWriter, r *http.Request) {
// describeCLI fills everything the approval page says about a live login,
// for both ways of reaching it (the link's GET and the typed code's POST
// continue), so neither can describe a login less truthfully than the other.
+//
+// A link request is described with the accounts the approver may link to,
+// and the page takes its title.
func (s *Server) describeCLI(p *cliPage, req *CLIAuthRequest, now time.Time) {
p.Request = req
p.Place = s.cliPlaceFor(req.RemoteAddr)
p.Started = now.Sub(req.CreatedAt)
+ if req.IsLink() {
+ p.Title = copyLD01
+ p.LinkAccounts = s.linkableAccounts(p.Address)
+ }
+}
+
+// linkableAccounts are the accounts address may link a deployment to: those
+// where it holds a role that creates apps (linkRoleCreates), the role
+// handleAPICreateApp admits. A failed read is no account.
+func (s *Server) linkableAccounts(address string) []Account {
+ accts, err := s.store.AccountsFor(address)
+ if err != nil {
+ log.Printf("console: link approval: accounts for %s: %v", address, err)
+ return nil
+ }
+ var out []Account
+ for _, a := range accts {
+ if linkRoleCreates(a.Role) {
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
+// linkApprovalAccount resolves the account a link approval names (its sqid)
+// among the approver's linkable accounts. Anything else, a forged sqid, an
+// account the approver is not in, a role that does not create apps, is not
+// found.
+func (s *Server) linkApprovalAccount(address, sqid string) (*Account, bool) {
+ if sqid == "" {
+ return nil, false
+ }
+ for _, a := range s.linkableAccounts(address) {
+ if a.Sqid == sqid {
+ return &a, true
+ }
+ }
+ return nil, false
}
// cliBudgetOpen reports whether neither key is over its guess budget. It is
@@ -1121,13 +1262,31 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
// Read the label first so the decided page can name the agent. A
// failed read changes nothing: the decision below reports the error
// and spends the budget exactly as before.
- if req, lerr := s.store.CLIAuthByUserCode(code, now); lerr == nil {
+ req, lerr := s.store.CLIAuthByUserCode(code, now)
+ if lerr == nil {
p.Label = req.Label
}
var err error
- if action == "deny" {
+ switch {
+ case action == "deny":
err = s.store.DenyCLIAuth(code, now)
- } else {
+ case lerr == nil && req.IsLink():
+ // A link is approved FOR an account, which must be one the
+ // approver may create apps in. A posted sqid outside that set
+ // (forged, or the role lost since the page) is LD-C07, the
+ // request untouched. ApproveCLIAuth never approves a link
+ // request, so no other branch can either.
+ acct, ok := s.linkApprovalAccount(addr, r.FormValue("account"))
+ if !ok {
+ p.Error = copyLD07
+ s.describeCLI(&p, req, now)
+ s.renderCLI(w, http.StatusForbidden, "cli_approve", p)
+ return
+ }
+ if err = s.store.ApproveLinkAuth(code, addr, acct.ID, now); err == nil {
+ p.LinkHome, p.LinkAccount = req.LinkName, acct.Name
+ }
+ default:
err = s.store.ApproveCLIAuth(code, addr, now)
}
if err != nil {
diff --git a/internal/console/authstore.go b/internal/console/authstore.go
index 406bf0234..c39471331 100644
--- a/internal/console/authstore.go
+++ b/internal/console/authstore.go
@@ -88,8 +88,17 @@ type CLIAuthRequest struct {
RemoteAddr string
CreatedAt time.Time
ExpiresAt time.Time
+ // Purpose is "" for a person's login and cliPurposeLink for a home
+ // deployment asking to link (linked deployments spec §5.1). LinkName is
+ // the name that deployment gave itself, a link request's only.
+ Purpose string
+ LinkName string
}
+// IsLink reports whether this request asks for a link credential rather
+// than a person's login. A template cannot see cliPurposeLink.
+func (r CLIAuthRequest) IsLink() bool { return r.Purpose == cliPurposeLink }
+
// CLIToken is one issued credential as its owner sees it on the console. ID
// is the token's sha256, which is safe to put in a page and in a form: it
// names the row without being the bearer secret.
@@ -275,6 +284,13 @@ func (s *Store) migrateCLIAuth() error {
// scope is a team credential's scope name (team-scoped credentials
// §3); '' for every other row, a person's token included.
`ALTER TABLE cli_tokens ADD COLUMN scope TEXT NOT NULL DEFAULT ''`,
+ // A login request's purpose: '' is a person's login, the only kind
+ // before linked deployments; 'link' is a home deployment asking for
+ // a link credential, with the name it gave itself and, once
+ // approved, the account the approver chose (spec §5.1).
+ `ALTER TABLE cli_auth_requests ADD COLUMN purpose TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE cli_auth_requests ADD COLUMN link_name TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE cli_auth_requests ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0`,
} {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
@@ -364,16 +380,24 @@ func newCredentialID() (string, error) {
return hex.EncodeToString(b), nil
}
-// The three token kinds cli_tokens holds. The user kind is the empty string
-// on purpose: it is what every row written before the app kind existed
-// already says, so the default IS the safe answer. cliKindService is the
-// principal that is not an address (see svcprincipal.go).
+// The token kinds cli_tokens holds. The user kind is the empty string on
+// purpose: it is what every row written before the app kind existed already
+// says, so the default IS the safe answer. cliKindService is the principal
+// that is not an address (see svcprincipal.go). cliKindLink is a linked
+// deployment's credential (links_store.go): bound to one account and one
+// link (its name column is the link ID), minted only by link approval,
+// never expiring, ended only by rotate and unlink.
const (
cliKindUser = ""
cliKindApp = "app"
cliKindService = "service"
+ cliKindLink = "link"
)
+// cliPurposeLink is a login request's purpose when a home deployment asks
+// for a link credential (POST /auth/cli/start {"purpose":"link"}).
+const cliPurposeLink = "link"
+
// newUserCode mints the typed code, grouped XXXX-XXXX so it can be read out
// and typed back without losing your place.
func newUserCode() (string, error) {
@@ -420,6 +444,20 @@ func NormalizeUserCode(in string) string {
// Housekeeping on the write path, the same idiom handleContinue uses: expired
// requests and tokens are dropped here rather than by a sweeper nobody runs.
func (s *Store) NewCLIAuth(label, remoteAddr string, now time.Time) (userCode, deviceCode string, err error) {
+ return s.newCLIAuth(label, remoteAddr, "", "", now)
+}
+
+// NewLinkAuth opens a link request: NewCLIAuth for a home deployment that
+// calls itself name. Approving it needs an account (ApproveLinkAuth), and
+// collecting it mints a link credential, never a person's token.
+func (s *Store) NewLinkAuth(name, label, remoteAddr string, now time.Time) (userCode, deviceCode string, err error) {
+ if name == "" {
+ return "", "", errors.New("console: a link request needs a name")
+ }
+ return s.newCLIAuth(label, remoteAddr, cliPurposeLink, name, now)
+}
+
+func (s *Store) newCLIAuth(label, remoteAddr, purpose, linkName string, now time.Time) (userCode, deviceCode string, err error) {
s.PurgeCLIAuth(now)
deviceCode, err = randomToken()
if err != nil {
@@ -433,10 +471,10 @@ func (s *Store) NewCLIAuth(label, remoteAddr string, now time.Time) (userCode, d
return "", "", err
}
_, err = s.db.Exec(`INSERT INTO cli_auth_requests
-(code_hash, user_code, label, remote_addr, state, created_at, expires_at)
-VALUES (?, ?, ?, ?, ?, ?, ?)`,
+(code_hash, user_code, label, remote_addr, state, created_at, expires_at, purpose, link_name)
+VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
hashToken(deviceCode), userCode, label, remoteAddr, CLIAuthPending,
- now.Unix(), now.Add(CLIAuthTTL).Unix())
+ now.Unix(), now.Add(CLIAuthTTL).Unix(), purpose, linkName)
if err == nil {
return userCode, deviceCode, nil
}
@@ -474,8 +512,10 @@ func (s *Store) PurgeCLIAuth(now time.Time) {
// expires_at = 0 means "never" (app tokens, see NewAppToken) and must be
// excluded from a sweep that compares against the clock — 0 is less than
// every now, so an unguarded sweep would delete exactly the credentials
- // that are supposed to outlive it.
- s.db.Exec(`DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ?`, now.Unix())
+ // that are supposed to outlive it. A link credential is excluded by kind
+ // as well as by its 0: only rotate and unlink end one, because only they
+ // also end its channel.
+ s.db.Exec(`DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ? AND kind != ?`, now.Unix(), cliKindLink)
}
// CLIAuthByUserCode resolves a typed code to the request it names, for the
@@ -485,9 +525,9 @@ func (s *Store) CLIAuthByUserCode(userCode string, now time.Time) (*CLIAuthReque
var r CLIAuthRequest
var created, expires int64
var state string
- err := s.db.QueryRow(`SELECT user_code, label, remote_addr, state, created_at, expires_at
+ err := s.db.QueryRow(`SELECT user_code, label, remote_addr, state, created_at, expires_at, purpose, link_name
FROM cli_auth_requests WHERE user_code = ?`, NormalizeUserCode(userCode)).
- Scan(&r.UserCode, &r.Label, &r.RemoteAddr, &state, &created, &expires)
+ Scan(&r.UserCode, &r.Label, &r.RemoteAddr, &state, &created, &expires, &r.Purpose, &r.LinkName)
if err == sql.ErrNoRows {
return nil, errors.New("console: no such login code")
}
@@ -504,22 +544,45 @@ FROM cli_auth_requests WHERE user_code = ?`, NormalizeUserCode(userCode)).
// ApproveCLIAuth records that address approved the request. The token is NOT
// minted here: it is minted when the CLI collects it (PollCLIAuth), so no
-// bearer credential is ever at rest waiting to be picked up.
+// bearer credential is ever at rest waiting to be picked up. It approves a
+// person's login only: a link request is approved by ApproveLinkAuth, with
+// an account, and is "no such code" here.
func (s *Store) ApproveCLIAuth(userCode, address string, now time.Time) error {
- return s.decideCLIAuth(userCode, address, CLIAuthApproved, now)
+ res, err := s.db.Exec(`UPDATE cli_auth_requests SET state = ?, address = ?
+WHERE user_code = ? AND state = ? AND expires_at >= ? AND purpose = ''`,
+ CLIAuthApproved, address, NormalizeUserCode(userCode), CLIAuthPending, now.Unix())
+ return decidedOne(res, err)
+}
+
+// ApproveLinkAuth records that address approved a LINK request for the
+// account accountID. The caller has checked that address may create apps in
+// that account (linkableAccounts); PollCLIAuth checks it again when it
+// mints. Like ApproveCLIAuth it mints nothing. A person's login request, an
+// account id of 0 and a decided or expired request are all "no such code".
+func (s *Store) ApproveLinkAuth(userCode, address string, accountID int64, now time.Time) error {
+ if accountID == 0 {
+ return errors.New("console: a link approval needs an account")
+ }
+ res, err := s.db.Exec(`UPDATE cli_auth_requests SET state = ?, address = ?, account_id = ?
+WHERE user_code = ? AND state = ? AND expires_at >= ? AND purpose = ?`,
+ CLIAuthApproved, address, accountID, NormalizeUserCode(userCode), CLIAuthPending, now.Unix(), cliPurposeLink)
+ return decidedOne(res, err)
}
// DenyCLIAuth is the "that wasn't me" button. A denied request is final:
// approving it afterwards is refused, so a mis-click cannot be walked back
-// into a credential by whoever is holding the terminal.
+// into a credential by whoever is holding the terminal. It denies a link
+// request exactly as a person's login.
func (s *Store) DenyCLIAuth(userCode string, now time.Time) error {
- return s.decideCLIAuth(userCode, "", CLIAuthDenied, now)
+ res, err := s.db.Exec(`UPDATE cli_auth_requests SET state = ?, address = ''
+WHERE user_code = ? AND state = ? AND expires_at >= ?`,
+ CLIAuthDenied, NormalizeUserCode(userCode), CLIAuthPending, now.Unix())
+ return decidedOne(res, err)
}
-func (s *Store) decideCLIAuth(userCode, address, state string, now time.Time) error {
- res, err := s.db.Exec(`UPDATE cli_auth_requests SET state = ?, address = ?
-WHERE user_code = ? AND state = ? AND expires_at >= ?`,
- state, address, NormalizeUserCode(userCode), CLIAuthPending, now.Unix())
+// decidedOne is a decision's outcome: one row moved, or the code had expired
+// or was already used.
+func decidedOne(res sql.Result, err error) error {
if err != nil {
return err
}
@@ -543,63 +606,115 @@ WHERE user_code = ? AND state = ? AND expires_at >= ?`,
// used since it was issued" is exactly the thing the tokens page exists to
// show.
func (s *Store) PollCLIAuth(deviceCode string, now time.Time) (status, rawToken, address string, err error) {
+ res, err := s.pollCLIAuth(deviceCode, now)
+ return res.Status, res.Token, res.Address, err
+}
+
+// cliPollResult is one poll's outcome. Token, Address and the link fields
+// are set only when Status is CLIAuthApproved; LinkID, AccountID and
+// AccountSqid only for a link request (Purpose cliPurposeLink).
+type cliPollResult struct {
+ Status, Token, Address string
+ Purpose string
+ LinkID string
+ AccountID int64
+ AccountSqid string
+}
+
+// pollCLIAuth is PollCLIAuth with the link half. For an approved person's
+// login it mints a user token as it always has. For an approved LINK
+// request it mints, in the same transaction that burns the request, the
+// link credential (cli_tokens kind 'link', bound to the account, name = the
+// link ID, never expiring) and its links row (the token's hash, generation
+// 1). The caller then writes the channel from that row (syncLinkChannel).
+//
+// The approver's role is checked again here, at the mint: an approver who
+// lost the role, or an account deleted, between the approval and the
+// collection mints nothing, and the request answers denied and is burnt.
+func (s *Store) pollCLIAuth(deviceCode string, now time.Time) (cliPollResult, error) {
if deviceCode == "" {
- return CLIAuthUnknown, "", "", nil
+ return cliPollResult{Status: CLIAuthUnknown}, nil
}
tx, err := s.db.Begin()
if err != nil {
- return "", "", "", err
+ return cliPollResult{}, err
}
defer tx.Rollback()
hash := hashToken(deviceCode)
- var storedHash, state, label, remote string
- var expires int64
- err = tx.QueryRow(`SELECT code_hash, state, address, label, remote_addr, expires_at
+ var storedHash, state, address, label, remote, purpose, linkName string
+ var expires, accountID int64
+ err = tx.QueryRow(`SELECT code_hash, state, address, label, remote_addr, expires_at, purpose, link_name, account_id
FROM cli_auth_requests WHERE code_hash = ?`, hash).
- Scan(&storedHash, &state, &address, &label, &remote, &expires)
+ Scan(&storedHash, &state, &address, &label, &remote, &expires, &purpose, &linkName, &accountID)
if err == sql.ErrNoRows {
- return CLIAuthUnknown, "", "", nil
+ return cliPollResult{Status: CLIAuthUnknown}, nil
}
if err != nil {
- return "", "", "", err
+ return cliPollResult{}, err
}
// Belt and braces over the indexed lookup: the comparison that decides
// whether this caller holds the secret is constant time.
if subtle.ConstantTimeCompare([]byte(storedHash), []byte(hash)) != 1 {
- return CLIAuthUnknown, "", "", nil
+ return cliPollResult{Status: CLIAuthUnknown}, nil
}
if now.Unix() > expires {
- return CLIAuthExpired, "", "", nil
+ return cliPollResult{Status: CLIAuthExpired}, nil
}
switch state {
case CLIAuthPending:
- return CLIAuthPending, "", "", nil
+ return cliPollResult{Status: CLIAuthPending}, nil
case CLIAuthDenied:
- return CLIAuthDenied, "", "", nil
+ return cliPollResult{Status: CLIAuthDenied}, nil
case CLIAuthApproved:
default:
- return CLIAuthUnknown, "", "", nil
+ return cliPollResult{Status: CLIAuthUnknown}, nil
}
raw, err := randomToken()
if err != nil {
- return "", "", "", err
+ return cliPollResult{}, err
}
- if _, err := tx.Exec(`INSERT INTO cli_tokens
+ out := cliPollResult{Status: CLIAuthApproved, Token: raw, Address: address, Purpose: purpose}
+ switch purpose {
+ case "":
+ if _, err := tx.Exec(`INSERT INTO cli_tokens
(token_hash, address, label, remote_addr, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?)`,
- hashToken(raw), address, label, remote, now.Unix(), now.Add(CLITokenTTL).Unix()); err != nil {
- return "", "", "", err
+ hashToken(raw), address, label, remote, now.Unix(), now.Add(CLITokenTTL).Unix()); err != nil {
+ return cliPollResult{}, err
+ }
+ case cliPurposeLink:
+ sqid, ok, err := linkApproverHolds(tx, accountID, address)
+ if err != nil {
+ return cliPollResult{}, err
+ }
+ if !ok {
+ if _, err := tx.Exec(`DELETE FROM cli_auth_requests WHERE code_hash = ?`, hash); err != nil {
+ return cliPollResult{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return cliPollResult{}, err
+ }
+ return cliPollResult{Status: CLIAuthDenied}, nil
+ }
+ linkID, err := mintLinkTx(tx, accountID, linkName, address, remote, raw, now)
+ if err != nil {
+ return cliPollResult{}, err
+ }
+ out.LinkID, out.AccountID, out.AccountSqid = linkID, accountID, sqid
+ default:
+ // A purpose this binary did not write mints nothing.
+ return cliPollResult{Status: CLIAuthUnknown}, nil
}
// Burn the request in the same transaction that mints the token: the two
// must never be separable, or a crash could hand out two tokens for one
// approval.
if _, err := tx.Exec(`DELETE FROM cli_auth_requests WHERE code_hash = ?`, hash); err != nil {
- return "", "", "", err
+ return cliPollResult{}, err
}
if err := tx.Commit(); err != nil {
- return "", "", "", err
+ return cliPollResult{}, err
}
- return CLIAuthApproved, raw, address, nil
+ return out, nil
}
// NewAppToken mints a credential an APP holds, bound to one account and one
@@ -714,10 +829,14 @@ func scanCLITokenRows(rows *sql.Rows) ([]CLIToken, error) {
// render here as an unbadged, still-live, still-revocable row — the comment
// above already promised "live", and until this filter the query did not
// keep that promise.
+//
+// A link credential is not listed: its address is the person who approved
+// the link, but it does not speak as them, and it is managed (rotated,
+// unlinked) on the account, never revoked from a person's settings.
func (s *Store) CLITokens(address string) ([]CLIToken, error) {
rows, err := s.db.Query(`SELECT token_hash, address, label, remote_addr, kind, account_id, app,
role, name, created_at, expires_at, last_used, revoked_at, rotated_at, rungs, commands, scope
-FROM cli_tokens WHERE address = ? AND revoked_at = 0 ORDER BY created_at DESC, token_hash`, address)
+FROM cli_tokens WHERE address = ? AND revoked_at = 0 AND kind != ? ORDER BY created_at DESC, token_hash`, address, cliKindLink)
if err != nil {
return nil, err
}
@@ -725,7 +844,9 @@ FROM cli_tokens WHERE address = ? AND revoked_at = 0 ORDER BY created_at DESC, t
}
// RevokeCLIToken kills one token by its listing id, scoped to its owner: an
-// id is not a secret, so the address is what makes this safe.
+// id is not a secret, so the address is what makes this safe. A link
+// credential is "no such token" here: only rotate and unlink end one,
+// because only they also end its channel in the hub.
func (s *Store) RevokeCLIToken(address, id string) error {
return s.RevokeCLITokenContext(context.Background(), address, id)
}
@@ -746,8 +867,8 @@ func (s *Store) RevokeCLITokenContext(ctx context.Context, address, id string) e
}
var accountID int64
var app string
- err := s.db.QueryRowContext(ctx, `SELECT account_id, app FROM cli_tokens WHERE token_hash = ? AND address = ?`,
- id, address).Scan(&accountID, &app)
+ err := s.db.QueryRowContext(ctx, `SELECT account_id, app FROM cli_tokens WHERE token_hash = ? AND address = ? AND kind != ?`,
+ id, address, cliKindLink).Scan(&accountID, &app)
if errors.Is(err, sql.ErrNoRows) {
return errNoSuchCLIToken
}
@@ -760,7 +881,7 @@ func (s *Store) RevokeCLITokenContext(ctx context.Context, address, id string) e
}
func (s *Store) claimRawRevokeCLIToken(address, id string) error {
- res, err := s.db.Exec(`DELETE FROM cli_tokens WHERE token_hash = ? AND address = ?`, id, address)
+ res, err := s.db.Exec(`DELETE FROM cli_tokens WHERE token_hash = ? AND address = ? AND kind != ?`, id, address, cliKindLink)
if err != nil {
return err
}
@@ -785,7 +906,8 @@ func (s *Store) RevokeCLITokenValue(rawToken string) error {
// DELETE matches on the hash alone, so it removes a legacy kind='app' or a
// service row exactly as it removes a person's: the only route that calls it
// sits behind cliUser, which admits person tokens (app ”) alone, but the method
-// does not rely on that. A row naming an app incarnation is admitted for that
+// does not rely on that. A link credential is never removed here (only rotate
+// and unlink end one). A row naming an app incarnation is admitted for that
// app first, as RevokeCLITokenContext and NewAppToken are; a token that matches
// nothing is not an error, as before.
func (s *Store) RevokeCLITokenValueContext(ctx context.Context, rawToken string) error {
@@ -795,7 +917,7 @@ func (s *Store) RevokeCLITokenValueContext(ctx context.Context, rawToken string)
}
var accountID int64
var app string
- err := s.db.QueryRowContext(ctx, `SELECT account_id, app FROM cli_tokens WHERE token_hash = ?`, hash).Scan(&accountID, &app)
+ err := s.db.QueryRowContext(ctx, `SELECT account_id, app FROM cli_tokens WHERE token_hash = ? AND kind != ?`, hash, cliKindLink).Scan(&accountID, &app)
if errors.Is(err, sql.ErrNoRows) {
return nil
}
@@ -808,7 +930,7 @@ func (s *Store) RevokeCLITokenValueContext(ctx context.Context, rawToken string)
}
func (s *Store) claimRawRevokeCLITokenValue(hash string) error {
- _, err := s.db.Exec(`DELETE FROM cli_tokens WHERE token_hash = ?`, hash)
+ _, err := s.db.Exec(`DELETE FROM cli_tokens WHERE token_hash = ? AND kind != ?`, hash, cliKindLink)
return err
}
func (s *Store) NewAppToken(accountID int64, app, mintedBy, label string, now time.Time) (claimResult0 string, claimResult1 error) {
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index e6282e05d..7d41e2de6 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2373,6 +2373,7 @@ var claimFixtures = map[string]claimFixture{
"worker LogPlacementDiscrepancies": claimRead("logs region drift between the registry and instance records; writes nothing"),
"worker FleetRelabel": claimRead("off on a host-claim console, where no claim operation gates a relabel: it logs that and writes nothing"),
"worker ManagedFleets": claimRead("off on a host-claim console; no launch, cleanup, or database work"),
+ "worker LinkSync": claimNonApp("writes linked deployments' channels in the hub registry from the console's links rows, and records the sync on those rows; names no app"),
"worker PublishMovesConsole": claimNonApp("the moves console record (control/moves-console.json): the platform's moves protocol and key fingerprint; no app, and nothing with the moves switch off and no secrets key"),
"worker ReportApexSquats": claimRead("logs apex squats found in the registry; writes nothing"),
"worker StartRunSweep": claimRead("off on a host-claim console, where every run route refuses: it logs that and writes nothing"),
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go
index dff8f90fd..007d82750 100644
--- a/internal/console/claim_invariant_probes_worker_test.go
+++ b/internal/console/claim_invariant_probes_worker_test.go
@@ -91,6 +91,46 @@ var claimWorkerProbes = map[string]claimProbe{
msgPlacementDiscrepancy("drift.go.tito.io", "blog", "uk")),
// ---- nonApp: they write deployment state ----
+ "worker LinkSync": {
+ // A link minted with no channel written (the poll's first sync
+ // skipped, as when it fails): the worker's first pass writes the
+ // channel from the links row and records the sync on it.
+ setup: func(t *testing.T, cx *claimCase) {
+ now := time.Now()
+ userCode, deviceCode, err := cx.st.NewLinkAuth("shop-home", "operator@home", "192.0.2.9", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.st.ApproveLinkAuth(userCode, claimFxOwner, OpsAccountID, now); err != nil {
+ t.Fatal(err)
+ }
+ if res, err := cx.st.pollCLIAuth(deviceCode, now); err != nil || res.LinkID == "" {
+ t.Fatalf("mint the link: %+v %v", res, err)
+ }
+ },
+ do: claimWorkerReply("LinkSync"),
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ var id, hash string
+ if err := cx.st.db.QueryRow(`SELECT id, token_hash FROM links`).Scan(&id, &hash); err != nil {
+ return "no links row: " + err.Error()
+ }
+ if ids, err := cx.st.linksNeedingSync(); err != nil || len(ids) != 0 {
+ return fmt.Sprintf("links still unsynced after the worker: %v %v", ids, err)
+ }
+ reg, err := cx.srv.linkReg()
+ if err != nil {
+ return err.Error()
+ }
+ auth, err := reg.LinkChannelAuth()
+ if err != nil {
+ return err.Error()
+ }
+ if auth[registry.LinkChannelName(id)] != hash {
+ return "the worker did not write the link's channel"
+ }
+ return ""
+ },
+ },
"worker PublishMovesConsole": {
setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.MovesEnabled = true },
do: claimWorkerReply("PublishMovesConsole"),
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go
index 94ee6752e..139668ec7 100644
--- a/internal/console/claim_workers.go
+++ b/internal/console/claim_workers.go
@@ -33,6 +33,7 @@ func (s *Server) registerClaimWorkers() {
"PublishMovesConsole": s.publishMovesConsoleWorker,
"FleetRelabel": s.StartFleetRelabel,
"ManagedFleets": s.StartManagedFleets,
+ "LinkSync": s.linkSyncLoop,
} {
s.jobs.declare(name)
e := claimEntry{Kind: "worker", Pattern: name, Handler: claimHandlerName(h)}
diff --git a/internal/console/jobs.go b/internal/console/jobs.go
index 533631d87..6b3cf490a 100644
--- a/internal/console/jobs.go
+++ b/internal/console/jobs.go
@@ -325,6 +325,7 @@ var jobLabels = map[string]string{
"StartEgressReport": "Outbound transfer report",
"FleetRelabel": "Fleet box placement",
"ManagedFleets": "Managed fleet provisioning", // COPY
+ "LinkSync": "Linked deployment sync",
}
// The job status words (OPS-80 to OPS-82).
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index e9371f10b..e5f79553e 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -72,6 +72,7 @@ var jobPassFuncs = map[string][]string{
"LogPlacementDiscrepancies": {"logPlacementDiscrepancies"},
"FleetRelabel": {"fleetRelabelPass", "relabelFleet", "planFirstLabelling", "writeRelabels"},
"ManagedFleets": {"managedFleetsPass", "stepManagedBox", "cleanupManagedBox"},
+ "LinkSync": {"linkSyncPass", "syncLinkChannel"},
}
// TestJobRegistryRecordsRuns pins the registry's bookkeeping (not
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go
new file mode 100644
index 000000000..28eabd5ac
--- /dev/null
+++ b/internal/console/links_auth_test.go
@@ -0,0 +1,759 @@
+package console
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// Linked deployments, Task 4 (spec 2026-11-10-linked-deployments-design.md
+// §5.1, §6.1): the link credential minted through the device-code flow.
+
+// newLinkFixture is the console fixture serving links: a tunnel host (the
+// hub's reserved hostname) and an apps domain.
+func newLinkFixture(t *testing.T, tunnelHost string) *consoleFixture {
+ t.Helper()
+ return newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) {
+ c.TunnelHost = tunnelHost
+ c.AppsDomain = "apps.example.com"
+ }})
+}
+
+// linkStart opens a link request the way a home console does.
+func linkStart(t *testing.T, fx *consoleFixture, name string) (userCode, deviceCode string) {
+ t.Helper()
+ status, start := postJSON(t, fx.ts.URL+"/auth/cli/start",
+ map[string]any{"purpose": "link", "name": name, "label": "operator@home"}, "")
+ if status != http.StatusOK {
+ t.Fatalf("link start = %d %v", status, start)
+ }
+ if str(t, start, "purpose") != "link" {
+ t.Fatalf("link start did not echo the purpose: %v", start)
+ }
+ return str(t, start, "user_code"), str(t, start, "device_code")
+}
+
+// linkCeremony starts a link, approves it in browser for the account sqid
+// (with step-up), and returns the poll answer.
+func linkCeremony(t *testing.T, fx *consoleFixture, browser *http.Client, name, sqid string) map[string]any {
+ t.Helper()
+ userCode, deviceCode := linkStart(t, fx, name)
+ code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve", url.Values{
+ "code": {userCode}, "action": {"approve"}, "account": {sqid}, "csrf": {sessionToken(t, fx, browser)}})
+ if code != http.StatusOK {
+ t.Fatalf("approve link = %d:\n%s", code, body)
+ }
+ _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "")
+ if str(t, poll, "status") != CLIAuthApproved || str(t, poll, "token") == "" {
+ t.Fatalf("link poll = %v, want approved with a token", poll)
+ }
+ return poll
+}
+
+func linkRegistryOf(t *testing.T, fx *consoleFixture) consoleRegistry {
+ t.Helper()
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return reg
+}
+
+func TestLinkApprovalMintsLinkToken(t *testing.T) {
+ // The hub stands in for the edge's /register: a TLS listener. Its
+ // certificate is the test's own, so the dial below fails at certificate
+ // verification, which is past the scheme check and inside a TLS
+ // handshake: the scheme the console handed back is one Dial accepts.
+ var hubConns sync.WaitGroup
+ hubConns.Add(1)
+ var once sync.Once
+ hub := httptest.NewUnstartedServer(http.NotFoundHandler())
+ hub.Config.ConnState = func(_ net.Conn, st http.ConnState) {
+ if st == http.StateNew {
+ once.Do(hubConns.Done)
+ }
+ }
+ hub.Config.ErrorLog = log.New(io.Discard, "", 0)
+ hub.StartTLS()
+ t.Cleanup(hub.Close)
+ hubHost := strings.TrimPrefix(hub.URL, "https://")
+
+ fx := newLinkFixture(t, hubHost)
+ browser := signInPaul(t, fx)
+
+ userCode, deviceCode := linkStart(t, fx, "shop-home")
+ // The approval page names the deployment and offers the account.
+ _, _, page := get(t, browser, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ for _, want := range []string{
+ esc(copyLD01),
+ esc(linkCopy(copyLD02, "home", "shop-home")),
+ esc(copyLD03),
+ esc(copyLD04),
+ esc(linkCopy(copyLD05, "home", "shop-home")),
+ esc(copyLD08),
+ `name="account"`,
+ `value="` + fx.sqid + `"`,
+ } {
+ if !strings.Contains(page, want) {
+ t.Fatalf("link approval page lacks %q:\n%s", want, page)
+ }
+ }
+ code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve", url.Values{
+ "code": {userCode}, "action": {"approve"}, "account": {fx.sqid}, "csrf": {sessionToken(t, fx, browser)}})
+ if code != http.StatusOK {
+ t.Fatalf("approve = %d:\n%s", code, body)
+ }
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatal(acct, err)
+ }
+ if want := esc(linkCopy(copyLD09, "home", "shop-home", "account", acct.Name)); !strings.Contains(body, want) {
+ t.Fatalf("approved page lacks %q:\n%s", want, body)
+ }
+ _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "")
+ token, linkID := str(t, poll, "token"), str(t, poll, "link_id")
+ if str(t, poll, "status") != CLIAuthApproved || token == "" {
+ t.Fatalf("poll = %v", poll)
+ }
+ if !registry.ValidLinkID(linkID) {
+ t.Fatalf("link_id %q is not a link ID", linkID)
+ }
+ if str(t, poll, "account") != fx.sqid {
+ t.Fatalf("poll account = %q, want %q", str(t, poll, "account"), fx.sqid)
+ }
+ tunnelURL := str(t, poll, "tunnel_url")
+ if tunnelURL != "https://"+hubHost+"/register" {
+ t.Fatalf("tunnel_url = %q, want https://%s/register", tunnelURL, hubHost)
+ }
+ if str(t, poll, "apps_domain") != "apps.example.com" {
+ t.Fatalf("apps_domain = %q", str(t, poll, "apps_domain"))
+ }
+
+ p, ok := fx.st.CLIPrincipal(token, time.Now())
+ if !ok || p.Kind != PrincipalLink || p.AccountID != acct.ID || p.LinkID != linkID {
+ t.Fatalf("CLIPrincipal = %+v %v, want a link principal for account %d, link %s", p, ok, acct.ID, linkID)
+ }
+ if p.Address != "" {
+ t.Fatalf("a link principal carries address %q; it carries no person's authority", p.Address)
+ }
+
+ reg := linkRegistryOf(t, fx)
+ owners, err := reg.LinkOwners()
+ if err != nil || owners[linkID] != fx.sqid {
+ t.Fatalf("LinkOwners = %v %v, want %s -> %s", owners, err, linkID, fx.sqid)
+ }
+ auth, err := reg.LinkChannelAuth()
+ if err != nil || auth[registry.LinkChannelName(linkID)] != hashToken(token) {
+ t.Fatalf("LinkChannelAuth = %v %v, want sha256 of the token", auth, err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ conn, err := tunnelclient.Dial(ctx, tunnelURL, registry.LinkChannelName(linkID), token)
+ if conn != nil {
+ conn.Close()
+ }
+ var verr *tls.CertificateVerificationError
+ if err == nil || !errors.As(err, &verr) {
+ t.Fatalf("Dial(%s) = %v, want a TLS dial that reaches certificate verification", tunnelURL, err)
+ }
+ hubConns.Wait()
+}
+
+func TestLinkTokenLifecycle(t *testing.T) {
+ fx := newLinkFixture(t, "tunnel.example.com")
+ browser := signInPaul(t, fx)
+ poll := linkCeremony(t, fx, browser, "blog-home", fx.sqid)
+ token, linkID := str(t, poll, "token"), str(t, poll, "link_id")
+ hash := hashToken(token)
+
+ var kind, name string
+ var expires int64
+ if err := fx.st.db.QueryRow(`SELECT kind, name, expires_at FROM cli_tokens WHERE token_hash = ?`, hash).
+ Scan(&kind, &name, &expires); err != nil {
+ t.Fatal(err)
+ }
+ if kind != cliKindLink || name != linkID || expires != 0 {
+ t.Fatalf("link token row = kind %q name %q expires_at %d, want link, %s, 0", kind, name, expires, linkID)
+ }
+ // A person's token minted beside it: the purge must reach that one, so
+ // the link token surviving is the purge's choice and not a skipped run.
+ person := cliToken(t, fx, "paul@keymail.dev", "code-lifecycle-person")
+
+ later := time.Now().Add(CLITokenTTL + time.Hour)
+ lastCLIPurge.Store(0)
+ fx.st.PurgeCLIAuth(later)
+ if _, ok := fx.st.CLIPrincipal(person, time.Now()); ok {
+ t.Fatal("the purge did not run: the person's token outlived its TTL")
+ }
+ if p, ok := fx.st.CLIPrincipal(token, later); !ok || p.Kind != PrincipalLink {
+ t.Fatalf("link token after the purge = %+v %v, want still a link principal", p, ok)
+ }
+
+ toks, err := fx.st.CLITokens("paul@keymail.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tk := range toks {
+ if tk.ID == hash {
+ t.Fatalf("CLITokens lists the link token: %+v", tk)
+ }
+ }
+
+ if err := fx.st.RevokeCLIToken("paul@keymail.dev", hash); err == nil {
+ t.Fatal("RevokeCLIToken reported revoking the link token")
+ }
+ if err := fx.st.RevokeAccountToken(OpsAccountID, hash, time.Now()); err == nil {
+ t.Fatal("RevokeAccountToken reported revoking the link token")
+ }
+ if err := fx.st.RevokeCLITokenValue(token); err != nil {
+ t.Fatal(err)
+ }
+ if p, ok := fx.st.CLIPrincipal(token, time.Now()); !ok || p.Kind != PrincipalLink {
+ t.Fatalf("link token after the person revoke doors = %+v %v, want still live", p, ok)
+ }
+ // The settings page's revoke door, by the id, from the approver's
+ // session: the same refusal through HTTP.
+ postGated(t, fx, browser, fx.ts.URL+"/auth/cli/tokens/revoke", url.Values{"id": {hash}, "csrf": {sessionToken(t, fx, browser)}})
+ if _, ok := fx.st.CLIPrincipal(token, time.Now()); !ok {
+ t.Fatal("the settings revoke door ended the link token")
+ }
+}
+
+func TestLinkApprovalNeedsCreateRole(t *testing.T) {
+ fx := newLinkFixture(t, "tunnel.example.com")
+ // kim owns account B and holds no role in the fixture's account A.
+ bID := testAccountID()
+ if err := fx.st.CreateAccount(bID, "kimb", "kims", "kim@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ kim := newBrowser(t)
+ fx.setUser("kim@keymail.dev")
+ signUp(t, fx, kim, "code-kim-link")
+
+ userCode, deviceCode := linkStart(t, fx, "shop-home")
+ _, _, page := get(t, kim, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ if !strings.Contains(page, `value="kimb"`) {
+ t.Fatalf("picker lacks kim's own account:\n%s", page)
+ }
+ if strings.Contains(page, `value="`+fx.sqid+`"`) {
+ t.Fatalf("picker offers account %s to a non-member:\n%s", fx.sqid, page)
+ }
+
+ code, _, body := postGated(t, fx, kim, fx.ts.URL+"/auth/cli/approve", url.Values{
+ "code": {userCode}, "action": {"approve"}, "account": {fx.sqid}, "csrf": {sessionToken(t, fx, kim)}})
+ if code != http.StatusForbidden || !strings.Contains(body, esc(copyLD07)) {
+ t.Fatalf("forged approve for account %s = %d, want 403 with LD-C07:\n%s", fx.sqid, code, body)
+ }
+ // No account at all is the same refusal, never a person login.
+ code, _, body = postGated(t, fx, kim, fx.ts.URL+"/auth/cli/approve", url.Values{
+ "code": {userCode}, "action": {"approve"}, "csrf": {sessionToken(t, fx, kim)}})
+ if code != http.StatusForbidden || !strings.Contains(body, esc(copyLD07)) {
+ t.Fatalf("approve with no account = %d, want 403 with LD-C07:\n%s", code, body)
+ }
+ _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "")
+ if str(t, poll, "status") != CLIAuthPending {
+ t.Fatalf("poll after refused approvals = %v, want pending", poll)
+ }
+ // A person-login approval cannot be pointed at a link request.
+ if err := fx.st.ApproveCLIAuth(userCode, "kim@keymail.dev", time.Now()); err == nil {
+ t.Fatal("ApproveCLIAuth approved a link request")
+ }
+
+ // Somebody with no account they may create apps in sees LD-C06 and no
+ // Approve button.
+ if _, err := fx.st.db.Exec(`DELETE FROM memberships WHERE address = ?`, "kim@keymail.dev"); err != nil {
+ t.Fatal(err)
+ }
+ _, _, page = get(t, kim, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ if !strings.Contains(page, esc(copyLD06)) || strings.Contains(page, `value="approve"`) {
+ t.Fatalf("approver with no account: want LD-C06 and no Approve:\n%s", page)
+ }
+}
+
+func TestPlainLoginUnchanged(t *testing.T) {
+ fx := newLinkFixture(t, "tunnel.example.com")
+ status, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "plain@laptop"}, "")
+ if status != http.StatusOK {
+ t.Fatalf("start = %d", status)
+ }
+ if _, has := start["purpose"]; has {
+ t.Fatalf("a plain start echoed a purpose: %v", start)
+ }
+ token := cliToken(t, fx, "paul@keymail.dev", "code-plain")
+ p, ok := fx.st.CLIPrincipal(token, time.Now())
+ if !ok || p.Kind != PrincipalUser || p.Address != "paul@keymail.dev" {
+ t.Fatalf("plain token = %+v %v, want the person", p, ok)
+ }
+ var n int
+ if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM links`).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("links rows after a plain login = %d %v", n, err)
+ }
+ // Any purpose other than link is refused; a link needs a name.
+ for _, body := range []map[string]any{
+ {"purpose": "fleet"},
+ {"purpose": ""},
+ {"purpose": "link"},
+ {"purpose": "link", "name": "\u202e"},
+ } {
+ if status, out := postJSON(t, fx.ts.URL+"/auth/cli/start", body, ""); status != http.StatusBadRequest {
+ t.Fatalf("start %v = %d %v, want 400", body, status, out)
+ }
+ }
+}
+
+// linkFaultRegistry fails PutLinkChannel while fail is above zero.
+type linkFaultRegistry struct {
+ consoleRegistry
+ mu sync.Mutex
+ fail int
+}
+
+func (f *linkFaultRegistry) PutLinkChannel(c registry.LinkChannel) (bool, error) {
+ f.mu.Lock()
+ if f.fail > 0 {
+ f.fail--
+ f.mu.Unlock()
+ return false, errors.New("injected registry failure")
+ }
+ f.mu.Unlock()
+ return f.consoleRegistry.PutLinkChannel(c)
+}
+
+func TestPollDeliversTokenWhenSyncFails(t *testing.T) {
+ fx := newLinkFixture(t, "tunnel.example.com")
+ real := linkRegistryOf(t, fx)
+ fault := &linkFaultRegistry{consoleRegistry: real, fail: 1}
+ fx.srv.linkRegistry = func() (consoleRegistry, error) { return fault, nil }
+ browser := signInPaul(t, fx)
+
+ poll := linkCeremony(t, fx, browser, "shop-home", fx.sqid)
+ token, linkID := str(t, poll, "token"), str(t, poll, "link_id")
+ auth, err := real.LinkChannelAuth()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, has := auth[registry.LinkChannelName(linkID)]; has {
+ t.Fatal("the failed sync wrote the channel")
+ }
+ ids, err := fx.st.linksNeedingSync()
+ if err != nil || len(ids) != 1 || ids[0] != linkID {
+ t.Fatalf("linksNeedingSync = %v %v, want [%s]", ids, err, linkID)
+ }
+ // The loop's pass (and Task 5's pre-handler sync, the same call) heals
+ // it from the console row alone.
+ if err := fx.srv.linkSyncPass(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ auth, err = real.LinkChannelAuth()
+ if err != nil || auth[registry.LinkChannelName(linkID)] != hashToken(token) {
+ t.Fatalf("after the pass LinkChannelAuth = %v %v, want the token's hash", auth, err)
+ }
+ if ids, err := fx.st.linksNeedingSync(); err != nil || len(ids) != 0 {
+ t.Fatalf("linksNeedingSync after healing = %v %v, want none", ids, err)
+ }
+}
+
+func TestSyncCannotResurrect(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ stage string
+ unlink bool
+ }{
+ {"rotate/paused-before-read", linkSyncBeforeRead, false},
+ {"rotate/paused-before-write", linkSyncBeforeWrite, false},
+ {"unlink/paused-before-read", linkSyncBeforeRead, true},
+ {"unlink/paused-before-write", linkSyncBeforeWrite, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := newLinkFixture(t, "tunnel.example.com")
+ browser := signInPaul(t, fx)
+ poll := linkCeremony(t, fx, browser, "shop-home", fx.sqid)
+ tokenA, linkID := str(t, poll, "token"), str(t, poll, "link_id")
+
+ paused, release := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ fx.srv.linkSyncHook = func(id, stage string) {
+ if id != linkID || stage != tc.stage {
+ return
+ }
+ first := false
+ once.Do(func() { first = true })
+ if first {
+ close(paused)
+ <-release
+ }
+ }
+ // A request authenticated with token A, paused at the barrier.
+ if p, ok := fx.st.CLIPrincipal(tokenA, time.Now()); !ok || p.Kind != PrincipalLink {
+ t.Fatalf("token A = %+v %v", p, ok)
+ }
+ done := make(chan error, 1)
+ go func() { done <- fx.srv.syncLinkChannel(context.Background(), linkID) }()
+ <-paused
+
+ var tokenB string
+ if tc.unlink {
+ if err := fx.st.RevokeLink(linkID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ var err error
+ if tokenB, err = fx.st.RotateLinkToken(linkID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if l, _ := fx.st.linkRow(linkID); l == nil || l.generation != 2 {
+ t.Fatalf("after rotate the row is %+v, want generation 2", l)
+ }
+ }
+ if err := fx.srv.syncLinkChannel(context.Background(), linkID); err != nil {
+ t.Fatal(err)
+ }
+ close(release)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+
+ auth, err := linkRegistryOf(t, fx).LinkChannelAuth()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, has := auth[registry.LinkChannelName(linkID)]
+ if tc.unlink {
+ if has {
+ t.Fatalf("the paused request resurrected the unlinked channel (hash %s)", got)
+ }
+ if _, ok := fx.st.CLIPrincipal(tokenA, time.Now()); ok {
+ t.Fatal("token A still resolves after unlink")
+ }
+ return
+ }
+ if got != hashToken(tokenB) {
+ t.Fatalf("registry holds %q, want token B's hash", got)
+ }
+ if _, ok := fx.st.CLIPrincipal(tokenA, time.Now()); ok {
+ t.Fatal("token A still resolves after rotate")
+ }
+ if p, ok := fx.st.CLIPrincipal(tokenB, time.Now()); !ok || p.LinkID != linkID {
+ t.Fatalf("token B = %+v %v", p, ok)
+ }
+ })
+ }
+}
+
+// ---- the walk: a link token is no credential at any existing door ---------
+
+// linkWalkFill is every placeholder the route declarations use. A
+// placeholder this table does not know fails the walk.
+var linkWalkFill = map[string]string{
+ "$": "",
+ "account": linkWalkSqid,
+ "sqid": linkWalkSqid,
+ "app": "kass",
+ "host": "web.go.tito.io",
+ "fleet": "edge",
+ "label": "box1",
+ "name": "hub",
+ "id": "deadbeefdeadbeef",
+ "level": "0",
+ "span": "1-1",
+ "version": "v1",
+ "address": "paul@keymail.dev",
+ "box": "box1",
+ "code": "WXYZ-4823",
+ "decision": "approve",
+ "domain": "example.com",
+ "file...": "app.css",
+ "hash": "deadbeef",
+ "jobID": "deadbeefdeadbeef",
+ "ledger": "usage",
+ "operationID": "deadbeefdeadbeef",
+ "region": "eu-west-1",
+ "route...": "a/b",
+ "rule": "rule",
+ "section": "general",
+ "token": "deadbeefdeadbeef",
+}
+
+const linkWalkSqid = "lnkwalk"
+
+var linkWalkPlaceholder = regexp.MustCompile(`\{([^{}]*)\}`)
+
+// linkWalkRequest is one declaration as a concrete request.
+func linkWalkRequest(t *testing.T, pattern string) (method, path string) {
+ t.Helper()
+ method, path = http.MethodGet, pattern
+ if m, rest, ok := strings.Cut(pattern, " "); ok {
+ method, path = m, rest
+ }
+ path = linkWalkPlaceholder.ReplaceAllStringFunc(path, func(ph string) string {
+ v, ok := linkWalkFill[ph[1:len(ph)-1]]
+ if !ok {
+ t.Fatalf("route %q uses placeholder %s, which linkWalkFill does not fill", pattern, ph)
+ }
+ return v
+ })
+ return method, path
+}
+
+// linkWalkWorld is one console configuration the walk runs against.
+type linkWalkWorld struct {
+ name string
+ cfg func(t *testing.T) Config
+ open func(t *testing.T) *Store
+}
+
+func linkWalkWorlds() []linkWalkWorld {
+ return []linkWalkWorld{
+ {
+ // gateDemo, gateNoHostClaim, gateMoves.
+ name: "demo-moves",
+ cfg: func(t *testing.T) Config {
+ c := demoTestDeploymentConfig(t)
+ c.Keymail = "https://keymail.example"
+ c.MovesEnabled = true
+ return c
+ },
+ open: func(t *testing.T) *Store { st, _ := demoTestStore(t); return st },
+ },
+ {
+ // gateHostClaim, gateRegionHA, gateMoves.
+ name: "host-claim-region-ha-moves",
+ cfg: func(*testing.T) Config {
+ return Config{Origin: "https://console.example", Keymail: "https://keymail.example",
+ HostClaim: true, RegionHA: true, MovesEnabled: true}
+ },
+ open: func(t *testing.T) *Store {
+ st, err := OpenGated(filepath.Join(t.TempDir(), "gated.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { st.Close() })
+ return st
+ },
+ },
+ }
+}
+
+// linkWalk serves world on a fresh console and sends one request per route
+// declaration that console registers, except those in skip, with the bearer
+// bearerFor mints in its store (nil: no Authorization header). It returns
+// each pattern's status (-1 for a transport failure), the store, and the
+// bearer.
+func linkWalk(t *testing.T, w linkWalkWorld, bearerFor func(*testing.T, *Store) string, skip map[string]bool) (map[string]int, *Store, string) {
+ t.Helper()
+ cfg := w.cfg(t)
+ st := w.open(t)
+ if err := st.CreateAccount(testAccountID(), linkWalkSqid, "walk", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ s, err := NewServer(cfg, st)
+ if err != nil {
+ t.Fatalf("%s: %v", w.name, err)
+ }
+ ts := httptest.NewServer(s)
+ t.Cleanup(ts.Close)
+ bearer := ""
+ if bearerFor != nil {
+ bearer = bearerFor(t, st)
+ }
+ client := &http.Client{
+ Timeout: 15 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }
+ out := map[string]int{}
+ for _, d := range routeDecls {
+ if d.Gate != nil && !d.Gate.holds(s.cfg) || skip[d.Pattern] {
+ continue
+ }
+ method, path := linkWalkRequest(t, d.Pattern)
+ var body io.Reader
+ if method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch {
+ body = strings.NewReader(`{}`)
+ }
+ req, err := http.NewRequest(method, ts.URL+path, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if bearerFor != nil {
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ out[d.Pattern] = -1
+ continue
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ out[d.Pattern] = res.StatusCode
+ }
+ return out, st, bearer
+}
+
+// mintWalkLink mints a link token in st through the store's own flow.
+func mintWalkLink(t *testing.T, st *Store) string {
+ t.Helper()
+ acct, err := st.AccountBySqid(linkWalkSqid)
+ if err != nil || acct == nil {
+ t.Fatal(acct, err)
+ }
+ now := time.Now()
+ userCode, deviceCode, err := st.NewLinkAuth("walk-home", "operator@home", "192.0.2.9", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := st.ApproveLinkAuth(userCode, "paul@keymail.dev", acct.ID, now); err != nil {
+ t.Fatal(err)
+ }
+ res, err := st.pollCLIAuth(deviceCode, now)
+ if err != nil || res.Status != CLIAuthApproved || res.LinkID == "" {
+ t.Fatalf("poll = %+v %v", res, err)
+ }
+ if p, ok := st.CLIPrincipal(res.Token, now); !ok || p.Kind != PrincipalLink {
+ t.Fatalf("minted link token = %+v %v", p, ok)
+ }
+ return res.Token
+}
+
+// mintWalkPerson mints a person's CLI token in st.
+func mintWalkPerson(t *testing.T, st *Store) string {
+ t.Helper()
+ raw, err := randomToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if _, err := st.db.Exec(`INSERT INTO cli_tokens (token_hash, address, label, remote_addr, created_at, expires_at)
+VALUES (?, ?, 'walk', '', ?, ?)`, hashToken(raw), "paul@keymail.dev", now.Unix(), now.Add(time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+// mintWalkFabricated is a bearer that was never minted.
+func mintWalkFabricated(t *testing.T, _ *Store) string {
+ t.Helper()
+ raw, err := randomToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+// linkWalkPresenceDoors are the doors where the PRESENCE of an
+// Authorization header, valid or not, selects a branch, so that no bearer at
+// all and an unknown bearer answer differently. At these a link token must
+// answer exactly as a bearer that was never minted. The walk fails if a
+// listed door does not in fact tell the two apart, so the list cannot grow
+// a door that does not need it.
+var linkWalkPresenceDoors = map[string]string{
+ // handleDemoPublish: "Presence, not validity, selects update.
+ // Duplicate or empty credentials cannot fall through to anonymous
+ // create." Any bearer is a demo update token or a 401.
+ "POST /api/demo/apps": "a bearer selects the demo update path",
+}
+
+func TestLinkTokenRefusedEverywhereElse(t *testing.T) {
+ walked := map[string]bool{}
+ reached := 0
+ for _, w := range linkWalkWorlds() {
+ t.Run(w.name, func(t *testing.T) {
+ none, _, _ := linkWalk(t, w, nil, nil)
+ fabricated, _, _ := linkWalk(t, w, mintWalkFabricated, nil)
+ link, st, token := linkWalk(t, w, mintWalkLink, nil)
+ // The person control skips the logout door, which would end
+ // its token half way through the walk.
+ person, _, _ := linkWalk(t, w, mintWalkPerson, map[string]bool{"POST /auth/cli/revoke": true})
+ for pattern, want := range none {
+ walked[pattern] = true
+ if want == -1 {
+ t.Errorf("%s: no-bearer request failed in transport", pattern)
+ }
+ got := link[pattern]
+ if got != fabricated[pattern] {
+ t.Errorf("%s: link token = %d, a never-minted bearer = %d", pattern, got, fabricated[pattern])
+ }
+ if _, presence := linkWalkPresenceDoors[pattern]; presence {
+ if fabricated[pattern] == want {
+ t.Errorf("%s is listed as a bearer-presence door but answers %d with and without a bearer", pattern, want)
+ }
+ } else if got != want {
+ t.Errorf("%s: link token = %d, no bearer = %d", pattern, got, want)
+ }
+ if p, has := person[pattern]; has && p != want {
+ reached++
+ }
+ }
+ // No door ended the link token: every door was asked with a
+ // live one.
+ if p, ok := st.CLIPrincipal(token, time.Now()); !ok || p.Kind != PrincipalLink {
+ t.Errorf("after the walk the link token = %+v %v, want still a live link principal", p, ok)
+ }
+ })
+ }
+ for _, d := range routeDecls {
+ if !walked[d.Pattern] {
+ t.Errorf("route %s was not walked: no world enables its gate", d.Pattern)
+ }
+ }
+ // The positive control: a person's token is a credential, so the same
+ // walk with it gets past the gate at the person's doors.
+ if reached < 50 {
+ t.Errorf("a person's token reached %d handlers the no-bearer walk did not, want at least 50; the walk proves nothing", reached)
+ }
+ // The reverse half, every kindLink door refusing person, app and
+ // service tokens, arrives with the kindLink doors (Task 5).
+}
+
+// TestLinkMintRechecksTheRole: an approver who loses the create role between
+// the approval and the collection mints nothing; the request answers denied
+// and is gone.
+func TestLinkMintRechecksTheRole(t *testing.T) {
+ st := openTestStore(t)
+ id := testAccountID()
+ if err := st.CreateAccount(id, "shopacct", "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ userCode, deviceCode, err := st.NewLinkAuth("shop-home", "operator@home", "192.0.2.9", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := st.ApproveLinkAuth(userCode, "paul@keymail.dev", id, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`DELETE FROM memberships WHERE account_id = ?`, id); err != nil {
+ t.Fatal(err)
+ }
+ res, err := st.pollCLIAuth(deviceCode, now)
+ if err != nil || res.Status != CLIAuthDenied || res.Token != "" {
+ t.Fatalf("poll after the role was lost = %+v %v, want denied and no token", res, err)
+ }
+ var links, tokens int
+ st.db.QueryRow(`SELECT COUNT(*) FROM links`).Scan(&links)
+ st.db.QueryRow(`SELECT COUNT(*) FROM cli_tokens WHERE kind = ?`, cliKindLink).Scan(&tokens)
+ if links != 0 || tokens != 0 {
+ t.Fatalf("minted %d links and %d link tokens for a lost role", links, tokens)
+ }
+ if res, _ := st.pollCLIAuth(deviceCode, now); res.Status != CLIAuthUnknown {
+ t.Fatalf("second poll = %+v, want the request burnt", res)
+ }
+}
diff --git a/internal/console/links_copy.go b/internal/console/links_copy.go
new file mode 100644
index 000000000..22ab81995
--- /dev/null
+++ b/internal/console/links_copy.go
@@ -0,0 +1,37 @@
+package console
+
+import "strings"
+
+// Linked deployments' approved copy (docs/drafts/linked-deployments-copy/
+// deck.md, APPROVED 2026-11-10), one constant per deck ID, verbatim.
+// Placeholders stay in braces and are filled by linkCopy.
+const (
+ // LD-C01: the link approval page's title and heading.
+ copyLD01 = "Approve a link"
+ // LD-C02: the approval page's lede.
+ copyLD02 = "A deployment calling itself {home} is asking to link to an account on Carloku."
+ // LD-C03: the note under the deployment's name.
+ copyLD03 = "This name was supplied by the deployment asking. Trust it only if it matches the deployment you are linking."
+ // LD-C04: the account picker's label.
+ copyLD04 = "Link it to"
+ // LD-C05: what approval grants.
+ copyLD05 = "Approving lets {home} publish its apps under this account, at addresses on Carloku. It can do nothing else here: it can't see or change your other apps, secrets, data or billing. You can unlink it at any time from the account's Fleet tab."
+ // LD-C06: the approver holds no account they may link.
+ copyLD06 = "You can't link a deployment to any of your accounts. Linking needs a role that can create apps in the account."
+ // LD-C07: approval refused (a forged POST, or the role lost).
+ copyLD07 = "You can't link a deployment to this account. Linking needs a role that can create apps in it."
+ // LD-C08: the not-me line; the buttons stay Approve and That wasn't me.
+ copyLD08 = "If you didn't just ask a deployment to link, press That wasn't me."
+ // LD-C09: the approved page.
+ copyLD09 = "Linked. {home} can now publish apps under {account}. Go back to it: it carries on by itself."
+)
+
+// linkCopy fills a deck string's {placeholders} from kv pairs (key, value,
+// key, value...). A key it is not given stays as written.
+func linkCopy(s string, kv ...string) string {
+ pairs := make([]string, 0, len(kv))
+ for i := 0; i+1 < len(kv); i += 2 {
+ pairs = append(pairs, "{"+kv[i]+"}", kv[i+1])
+ }
+ return strings.NewReplacer(pairs...).Replace(s)
+}
diff --git a/internal/console/links_store.go b/internal/console/links_store.go
new file mode 100644
index 000000000..76d61b2ef
--- /dev/null
+++ b/internal/console/links_store.go
@@ -0,0 +1,325 @@
+package console
+
+// Linked deployments, the serving console's record (spec
+// 2026-11-10-linked-deployments-design.md §5.1, §6.1).
+//
+// A home deployment links to an account through the device-code flow
+// (authcli.go, purpose "link"). Collecting an approved link request mints
+// two rows in one transaction: the link credential, a cli_tokens row of kind
+// 'link' bound to the account (its name column is the link ID), and this
+// file's links row. The links row is the authority for the link's channel in
+// the hub registry: token_hash is the sha256 of the current credential (one
+// secret, two uses: the console's bearer and the channel's dial-in) and
+// generation orders every change to it. syncLinkChannel (links_sync.go) is
+// the one writer of the channel and reads nothing but this row.
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+)
+
+// Link is one linked deployment as the serving console records it. Name is
+// what the home deployment calls itself (supplied by it, shown with that
+// caveat); CreatedBy is the person who approved the link. RevokedAt is zero
+// for a live link.
+type Link struct {
+ ID string
+ AccountID int64
+ Name string
+ CreatedBy string
+ CreatedAt time.Time
+ RevokedAt time.Time
+}
+
+// ErrNoLink is a link ID with no live row: never minted, or unlinked.
+var ErrNoLink = errors.New("console: no such link")
+
+// migrateLinks creates the links table. Additive and idempotent, called from
+// Store.migrate. synced_generation and revoke_synced record what the hub
+// registry was last told (syncLinkChannel), so linkSyncLoop can find a link
+// whose channel write failed.
+func (s *Store) migrateLinks() error {
+ for _, stmt := range []string{
+ `CREATE TABLE IF NOT EXISTS links (
+ id TEXT PRIMARY KEY,
+ account_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ created_by TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ revoked_at INTEGER NOT NULL DEFAULT 0,
+ token_hash TEXT NOT NULL,
+ generation INTEGER NOT NULL,
+ synced_generation INTEGER NOT NULL DEFAULT 0,
+ revoke_synced INTEGER NOT NULL DEFAULT 0
+);`,
+ `CREATE INDEX IF NOT EXISTS links_account ON links (account_id);`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// newLinkID mints a link ID: 12 lowercase hex characters from crypto/rand
+// (registry.ValidLinkID's grammar).
+func newLinkID() (string, error) {
+ b := make([]byte, 6)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// linkRoleCreates reports whether an account role may create apps, which is
+// the role linking needs (spec §5.1: the role `carlos deploy` of a new app
+// needs). handleAPICreateApp admits every member of the account, and the two
+// roles a membership holds are owner and member; anything else is refused.
+func linkRoleCreates(role string) bool { return role == RoleOwner || role == RoleMember }
+
+// linkApproverHolds reports, inside tx, whether address may still link to
+// accountID (a live account where address holds a role that creates apps),
+// with the account's sqid.
+func linkApproverHolds(tx *sql.Tx, accountID int64, address string) (sqid string, ok bool, err error) {
+ var role string
+ err = tx.QueryRow(`SELECT a.sqid, m.role FROM accounts a JOIN memberships m ON m.account_id = a.id
+WHERE a.id = ? AND m.address = ? AND a.deleted_at = 0`, accountID, address).Scan(&sqid, &role)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", false, nil
+ }
+ if err != nil {
+ return "", false, err
+ }
+ return sqid, linkRoleCreates(role), nil
+}
+
+// mintLinkTx writes, inside tx, a new link for accountID and its credential
+// raw: the cli_tokens row (kind 'link', name the link ID, expires_at 0) and
+// the links row (raw's hash, generation 1). It returns the link ID.
+func mintLinkTx(tx *sql.Tx, accountID int64, name, approvedBy, remote, raw string, now time.Time) (string, error) {
+ var id string
+ for attempt := 0; ; attempt++ {
+ if attempt == 3 {
+ return "", errors.New("console: could not mint a free link id")
+ }
+ var err error
+ if id, err = newLinkID(); err != nil {
+ return "", err
+ }
+ var one int
+ err = tx.QueryRow(`SELECT 1 FROM links WHERE id = ?`, id).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ break
+ }
+ if err != nil {
+ return "", err
+ }
+ }
+ hash := hashToken(raw)
+ if _, err := tx.Exec(`INSERT INTO cli_tokens
+(token_hash, address, label, remote_addr, created_at, expires_at, kind, account_id, name)
+VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)`, hash, approvedBy, name, remote, now.Unix(), cliKindLink, accountID, id); err != nil {
+ return "", err
+ }
+ if _, err := tx.Exec(`INSERT INTO links (id, account_id, name, created_by, created_at, token_hash, generation)
+VALUES (?, ?, ?, ?, ?, ?, 1)`, id, accountID, name, approvedBy, now.Unix(), hash); err != nil {
+ return "", err
+ }
+ return id, nil
+}
+
+// linkState is a links row whole: the Link, the account's sqid ("" when the
+// account row is gone), and the channel fields syncLinkChannel reads.
+type linkState struct {
+ Link
+ sqid string
+ tokenHash string
+ generation int64
+ syncedGeneration int64
+ revokeSynced bool
+}
+
+const linkStateCols = `l.id, l.account_id, l.name, l.created_by, l.created_at, l.revoked_at,
+COALESCE(a.sqid, ''), l.token_hash, l.generation, l.synced_generation, l.revoke_synced`
+
+func scanLinkState(scan func(...any) error) (*linkState, error) {
+ var l linkState
+ var created, revoked, revokeSynced int64
+ if err := scan(&l.ID, &l.AccountID, &l.Name, &l.CreatedBy, &created, &revoked,
+ &l.sqid, &l.tokenHash, &l.generation, &l.syncedGeneration, &revokeSynced); err != nil {
+ return nil, err
+ }
+ l.CreatedAt = time.Unix(created, 0).UTC()
+ if revoked != 0 {
+ l.RevokedAt = time.Unix(revoked, 0).UTC()
+ }
+ l.revokeSynced = revokeSynced != 0
+ return &l, nil
+}
+
+// linkRow reads one link's whole row; nil, nil when there is none.
+func (s *Store) linkRow(id string) (*linkState, error) {
+ l, err := scanLinkState(s.db.QueryRow(`SELECT `+linkStateCols+`
+FROM links l LEFT JOIN accounts a ON a.id = l.account_id WHERE l.id = ?`, id).Scan)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return l, err
+}
+
+// LinkByID returns one link, revoked or not; nil, nil when there is none.
+func (s *Store) LinkByID(id string) (*Link, error) {
+ l, err := s.linkRow(id)
+ if l == nil || err != nil {
+ return nil, err
+ }
+ return &l.Link, nil
+}
+
+// LinksForAccount lists an account's links, oldest first, revoked ones
+// included (an unlink in progress is still shown).
+func (s *Store) LinksForAccount(accountID int64) ([]Link, error) {
+ rows, err := s.db.Query(`SELECT `+linkStateCols+`
+FROM links l LEFT JOIN accounts a ON a.id = l.account_id WHERE l.account_id = ? ORDER BY l.created_at, l.id`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []Link
+ for rows.Next() {
+ l, err := scanLinkState(rows.Scan)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, l.Link)
+ }
+ return out, rows.Err()
+}
+
+// linksNeedingSync lists the links whose channel the hub registry has not
+// yet been told: a generation not yet written, or a revocation not yet
+// written. linkSyncLoop's work list.
+func (s *Store) linksNeedingSync() ([]string, error) {
+ rows, err := s.db.Query(`SELECT id FROM links
+WHERE synced_generation < generation OR (revoked_at != 0 AND revoke_synced = 0) ORDER BY id`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ out = append(out, id)
+ }
+ return out, rows.Err()
+}
+
+// markLinkSynced records that the registry now holds generation of link id
+// (and, when revoked, its revocation). The recorded generation only rises, so
+// a slower sync of an older row never lowers it.
+func (s *Store) markLinkSynced(id string, generation int64, revoked bool) error {
+ q := `UPDATE links SET synced_generation = MAX(synced_generation, ?) WHERE id = ?`
+ if revoked {
+ q = `UPDATE links SET synced_generation = MAX(synced_generation, ?), revoke_synced = 1 WHERE id = ?`
+ }
+ _, err := s.db.Exec(q, generation, id)
+ return err
+}
+
+// RotateLinkToken replaces a live link's credential in one transaction: a
+// new link token, the old one(s) revoked, and the links row given the new
+// hash at generation+1. It returns the new raw token. The caller then runs
+// syncLinkChannel, which moves the channel to the new hash. ErrNoLink for a
+// link that is missing or revoked.
+func (s *Store) RotateLinkToken(id string, now time.Time) (string, error) {
+ raw, err := randomToken()
+ if err != nil {
+ return "", err
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback()
+ var accountID, revoked int64
+ var name, createdBy string
+ err = tx.QueryRow(`SELECT account_id, name, created_by, revoked_at FROM links WHERE id = ?`, id).
+ Scan(&accountID, &name, &createdBy, &revoked)
+ if errors.Is(err, sql.ErrNoRows) || (err == nil && revoked != 0) {
+ return "", ErrNoLink
+ }
+ if err != nil {
+ return "", err
+ }
+ hash := hashToken(raw)
+ if _, err := tx.Exec(`UPDATE cli_tokens SET revoked_at = ? WHERE kind = ? AND name = ? AND revoked_at = 0`,
+ now.Unix(), cliKindLink, id); err != nil {
+ return "", err
+ }
+ if _, err := tx.Exec(`INSERT INTO cli_tokens
+(token_hash, address, label, remote_addr, created_at, expires_at, kind, account_id, name)
+VALUES (?, ?, ?, '', ?, 0, ?, ?, ?)`, hash, createdBy, name, now.Unix(), cliKindLink, accountID, id); err != nil {
+ return "", err
+ }
+ res, err := tx.Exec(`UPDATE links SET token_hash = ?, generation = generation + 1 WHERE id = ? AND revoked_at = 0`, hash, id)
+ if err != nil {
+ return "", err
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return "", fmt.Errorf("console: rotate link %s: %d rows, %v", id, n, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return "", err
+ }
+ return raw, nil
+}
+
+// RevokeLink ends a link on the console in one transaction: the links row's
+// revoked_at and its credential revoked. The caller then runs
+// syncLinkChannel, which revokes the channel and its forward rows in the
+// registry. Revoking a revoked link changes nothing and is not an error;
+// ErrNoLink for an ID with no row.
+func (s *Store) RevokeLink(id string, now time.Time) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var revoked int64
+ err = tx.QueryRow(`SELECT revoked_at FROM links WHERE id = ?`, id).Scan(&revoked)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ErrNoLink
+ }
+ if err != nil {
+ return err
+ }
+ if revoked == 0 {
+ if _, err := tx.Exec(`UPDATE links SET revoked_at = ? WHERE id = ? AND revoked_at = 0`, now.Unix(), id); err != nil {
+ return err
+ }
+ }
+ if _, err := tx.Exec(`UPDATE cli_tokens SET revoked_at = ? WHERE kind = ? AND name = ? AND revoked_at = 0`,
+ now.Unix(), cliKindLink, id); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// linkPrincipalLive reports whether a kind='link' credential (its hash,
+// account and link ID) is the live credential of a live link: the links
+// row exists, is not revoked, belongs to the same account, and holds this
+// hash as its current one.
+func (s *Store) linkPrincipalLive(hash string, accountID int64, linkID string) bool {
+ var acct, revoked int64
+ var current string
+ err := s.db.QueryRow(`SELECT account_id, revoked_at, token_hash FROM links WHERE id = ?`, linkID).
+ Scan(&acct, &revoked, &current)
+ return err == nil && revoked == 0 && acct == accountID && current == hash
+}
diff --git a/internal/console/links_sync.go b/internal/console/links_sync.go
new file mode 100644
index 000000000..50f10ba62
--- /dev/null
+++ b/internal/console/links_sync.go
@@ -0,0 +1,133 @@
+package console
+
+// The one writer of a link's channel in the hub registry (linked
+// deployments spec §6.1; Paul's choice 1, 2026-11-10).
+//
+// syncLinkChannel is the only production caller of the registry's
+// PutLinkChannel and RevokeLinkChannel. It reads the console's links row and
+// writes the registry from that row alone: never a hash, a generation or a
+// status taken from a request. Every event that changes a link changes the
+// row first, in one console transaction (mint, rotate, unlink), and then
+// asks for a sync. A sync may run late, twice or concurrently with another;
+// the registry applies a channel write only at a higher generation and never
+// after a revocation, so a sync that read an older row can only be refused,
+// and the last word is always the row's current state.
+//
+// A sync that fails leaves the row unsynced (synced_generation below
+// generation, or revoke_synced 0). linkSyncLoop finds those every ten
+// seconds and syncs them again, and Task 5's link doors sync before every
+// handler, so a failed registry write heals without any further call.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// linkSyncInterval is linkSyncLoop's period.
+const linkSyncInterval = 10 * time.Second
+
+// The stages syncLinkChannel reports to linkSyncHook (tests only).
+const (
+ linkSyncBeforeRead = "before-read"
+ linkSyncBeforeWrite = "before-write"
+)
+
+// linkReg is the registry a link sync writes.
+func (s *Server) linkReg() (consoleRegistry, error) {
+ if s.linkRegistry != nil {
+ return s.linkRegistry()
+ }
+ return openRegistry(s.cfg.Registry)
+}
+
+// syncLinkChannel writes linkID's channel in the hub registry from the
+// console's links row: PutLinkChannel at the row's generation with its
+// token hash for a live link, RevokeLinkChannel for a revoked one. On
+// success it records what the registry now holds (markLinkSynced). A link
+// with no row is an error and writes nothing.
+func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if s.linkSyncHook != nil {
+ s.linkSyncHook(linkID, linkSyncBeforeRead)
+ }
+ row, err := s.store.linkRow(linkID)
+ if err != nil {
+ return fmt.Errorf("link %s: read: %w", linkID, err)
+ }
+ if row == nil {
+ return fmt.Errorf("link %s: %w", linkID, ErrNoLink)
+ }
+ revoked := !row.RevokedAt.IsZero()
+ if !revoked && row.sqid == "" {
+ return fmt.Errorf("link %s: account %d has no row", linkID, row.AccountID)
+ }
+ reg, err := s.linkReg()
+ if err != nil {
+ return fmt.Errorf("link %s: open registry: %w", linkID, err)
+ }
+ if s.linkSyncHook != nil {
+ s.linkSyncHook(linkID, linkSyncBeforeWrite)
+ }
+ if revoked {
+ if _, err := reg.RevokeLinkChannel(linkID); err != nil {
+ return fmt.Errorf("link %s: revoke channel: %w", linkID, err)
+ }
+ } else {
+ // applied is false for a write the registry already holds, or one
+ // it refuses as older than what it holds or as after a
+ // revocation: in every case the registry is at or past this row,
+ // so the row is synced as far as this generation goes.
+ if _, err := reg.PutLinkChannel(registry.LinkChannel{
+ LinkID: linkID,
+ Account: row.sqid,
+ TokenHash: row.tokenHash,
+ Status: "active",
+ Generation: uint64(row.generation),
+ CreatedAt: row.CreatedAt,
+ }); err != nil {
+ return fmt.Errorf("link %s: put channel: %w", linkID, err)
+ }
+ }
+ if err := s.store.markLinkSynced(linkID, row.generation, revoked); err != nil {
+ return fmt.Errorf("link %s: record sync: %w", linkID, err)
+ }
+ return nil
+}
+
+// linkSyncLoop runs linkSyncPass now and then every linkSyncInterval until
+// ctx is done: the delivery retry for a channel write that failed. It reads
+// only the console database and writes only the registry.
+func (s *Server) linkSyncLoop(ctx context.Context) {
+ t := time.NewTicker(linkSyncInterval)
+ defer t.Stop()
+ for {
+ _ = s.jobs.Run(ctx, "LinkSync", s.linkSyncPass)
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ }
+}
+
+// linkSyncPass syncs every link the registry is behind on. One link's
+// failure does not stop the others; the pass returns them all joined.
+func (s *Server) linkSyncPass(ctx context.Context) error {
+ ids, err := s.store.linksNeedingSync()
+ if err != nil {
+ return fmt.Errorf("links needing sync: %w", err)
+ }
+ var errs []error
+ for _, id := range ids {
+ if err := s.syncLinkChannel(ctx, id); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index a9d2c1df9..ea64ec73b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1393,6 +1393,13 @@ type Server struct {
// its gate runs. Tests only: the write measurements stamp the moment
// the console has read a body's last byte (console-slow-writes).
cliBodyWrap func(*http.Request) io.ReadCloser
+ // linkRegistry, when non-nil, is the registry syncLinkChannel writes
+ // instead of openRegistry(cfg.Registry), and linkSyncHook, when
+ // non-nil, is called at each stage of a link sync (links_sync.go).
+ // Tests only: a registry that fails a write, and the barrier that
+ // pauses a sync between its steps.
+ linkRegistry func() (consoleRegistry, error)
+ linkSyncHook func(linkID, stage string)
// delegationZone and lookupCNAME are the wildcard-capability door's two
// seams (apidomains.go). delegationZone is cfg.DelegationZone, shape-
// validated and normalized once here (normalizeDelegationZone);
diff --git a/internal/console/store.go b/internal/console/store.go
index 799587967..ec8c98044 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -678,6 +678,10 @@ func (s *Store) migrate() error {
if err := s.migrateCLIAuth(); err != nil {
return err
}
+ // Linked deployments' own table (links_store.go), for the same reason.
+ if err := s.migrateLinks(); err != nil {
+ return err
+ }
// Passkey step-up's own tables (stepup.go), for the same reason.
if err := s.migrateStepUp(); err != nil {
return err
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index b8482c5ee..1eaa8ffa1 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -265,6 +265,7 @@ var claimSQLTables = map[string]claimSQLTable{
"move_log_outbox": {NonApp: "a moves audit outbox that stores no app name: rows are keyed by host, move and entry and bound to an instance incarnation, verified against the host's claim and record at every write, written only by the moves recovery and log passes, and purged with the incarnation"},
"edge_proof_seen": {NonApp: "single-row edge proof marker"},
"cli_auth_requests": {NonApp: "device-code logins in flight, keyed by code hash"},
+ "links": {NonApp: "linked deployments, keyed by link id and bound to an account; names no app"},
"step_ups": {NonApp: "passkey step-up marks, keyed by session hash"},
"claim_sql_identity": {NonApp: "private receipt database identity"},
"claim_sql_receipts": {NonApp: "private SQL effect receipts and fences"},
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go
index e56f50196..caa411545 100644
--- a/internal/console/svcprincipal.go
+++ b/internal/console/svcprincipal.go
@@ -33,14 +33,20 @@ import (
"github.com/carlosframework/platform/internal/svcrole"
)
-// PrincipalKind separates the two things a bearer token can be. It is a typed
+// PrincipalKind separates the things a bearer token can be. It is a typed
// constant rather than a string compare at each call site so that "is this a
// person?" cannot be written two subtly different ways in two files.
+//
+// PrincipalLink is a linked deployment's credential (links_store.go). It
+// carries no person's authority and no role: every existing gate refuses it
+// as if no bearer had been sent (cliGateRefused, serviceBinding,
+// sourceAdmission), and only the link doors admit it.
type PrincipalKind int
const (
PrincipalUser PrincipalKind = iota
PrincipalService
+ PrincipalLink
)
// Principal is one resolved caller.
@@ -75,6 +81,9 @@ type Principal struct {
// and never empty for a team principal: CLIPrincipal refuses a team
// row whose scope is empty or not canonical.
Scope string
+ // LinkID is a link principal's link (AccountID is its account). ""
+ // for every other kind.
+ LinkID string
}
// ErrServiceNameTaken is returned by NewServicePrincipal when the account
@@ -194,6 +203,17 @@ FROM cli_tokens WHERE token_hash = ?`, hash).
}
p = Principal{Kind: PrincipalService, Address: addr, AccountID: accountID, App: app, Role: r, Name: name, Rungs: scope,
CredentialID: credID, Commands: granted, Scope: teamScope}
+ case cliKindLink:
+ // A link credential is its link's current credential or nothing:
+ // the links row must be live, in the same account, and hold this
+ // hash (a rotated-away token is revoked as well, belt and braces).
+ // A row carrying an app, a role or any scope column is not one
+ // this console wrote. No Address: it speaks for no person.
+ if accountID == 0 || app != "" || role != "" || rungs != "" || commands != "" || teamScope != "" ||
+ !s.linkPrincipalLive(hash, accountID, name) {
+ return Principal{}, false
+ }
+ p = Principal{Kind: PrincipalLink, AccountID: accountID, LinkID: name}
default:
return Principal{}, false
}
@@ -531,8 +551,10 @@ func (s *Store) RevokeAccountToken(accountID int64, id string, now time.Time) er
if accountID == 0 {
return ErrNoServicePrincipal
}
+ // A link credential is bound to an account too, and is excluded: only
+ // rotate and unlink end one, because only they also end its channel.
res, err := s.db.Exec(`UPDATE cli_tokens SET revoked_at = ?
-WHERE token_hash = ? AND account_id = ? AND revoked_at = 0`, now.Unix(), id, accountID)
+WHERE token_hash = ? AND account_id = ? AND revoked_at = 0 AND kind != ?`, now.Unix(), id, accountID, cliKindLink)
if err != nil {
return err
}
@@ -570,7 +592,13 @@ WHERE token_hash = ? AND account_id = ? AND revoked_at = 0`, now.Unix(), id, acc
// The account id rather than the sqid because this string is never shown to
// anyone — it is a map key, and the id is what the resolver already has on
// the Principal without a further lookup.
+//
+// A LINK keys on its link ID: one budget per linked deployment, kept across
+// a rotation, and never the account's or its approver's.
func principalKey(p Principal) string {
+ if p.Kind == PrincipalLink {
+ return "link:" + p.LinkID
+ }
if p.Kind == PrincipalUser {
return p.Address
}
diff --git a/internal/console/templates/cli_approve.html b/internal/console/templates/cli_approve.html
index e89d33430..cda992e01 100644
--- a/internal/console/templates/cli_approve.html
+++ b/internal/console/templates/cli_approve.html
@@ -1,7 +1,42 @@
{{define "cli_approve"}}{{template "top" .}}
-<h1>{{.CLIText "cli.title"}}</h1>
+<h1>{{.Heading}}</h1>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
-{{if .Request}}
+{{if and .Request .Request.IsLink}}
+<p class="lede">{{.LinkLede}}</p>
+<p class="tile-value"><code>{{.Request.UserCode}}</code></p>
+<p><strong>{{.CLIText "cli.check"}}</strong></p>
+<div class="banner">
+ <p><strong>{{.Request.LinkName}}</strong>.
+ <span class="small">{{.LinkNote}}</span></p>
+ <p><strong>From</strong> {{emptyOrDash .Request.RemoteAddr}}{{if .Place.Text}}, {{.Place.Text}}{{end}}
+ {{- if .Place.Attribution}} <span class="small">(<a href="{{.Place.AttributionURL}}">{{.Place.Attribution}}</a>)</span>{{end}}</p>
+ <p class="small">{{.StartedText}} Expires {{fmtTime .Request.ExpiresAt}}</p>
+</div>
+{{if .LinkAccounts}}
+<p>{{.LinkGrant}}</p>
+<p>{{.LinkNotMe}}</p>
+<form class="signin" method="post" action="/auth/cli/approve">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <input type="hidden" name="code" value="{{.Request.UserCode}}">
+ <label for="link-account">{{.LinkPick}}</label>
+ <select id="link-account" name="account">
+ {{- range .LinkAccounts}}
+ <option value="{{.Sqid}}">{{.Name}} ({{.Sqid}})</option>
+ {{- end}}
+ </select>
+ <button type="submit" name="action" value="approve">Approve</button>
+ <button class="linkish" type="submit" name="action" value="deny">That wasn't me</button>
+</form>
+{{else}}
+<p>{{.LinkNone}}</p>
+<p>{{.LinkNotMe}}</p>
+<form class="signin" method="post" action="/auth/cli/approve">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <input type="hidden" name="code" value="{{.Request.UserCode}}">
+ <button class="linkish" type="submit" name="action" value="deny">That wasn't me</button>
+</form>
+{{end}}
+{{else if .Request}}
<p class="lede">{{.Lede}}</p>
<p class="tile-value"><code>{{.Request.UserCode}}</code></p>
<p><strong>{{.CLIText "cli.check"}}</strong></p>
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 62ea96268..2168b380a 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -395,6 +395,7 @@ route PUT /api/cli/system/geoip
route PUT /api/cli/system/managed-fleets
route PUT /api/cli/system/upload
worker FleetRelabel
+worker LinkSync
worker LogPlacementDiscrepancies
worker ManagedFleets
worker PublishMovesConsole