Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ local-up: local-tools
local-down: local-tools
PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py down

.PHONY: local-trust local-login local-llm-key local-google-oidc
.PHONY: local-trust local-login local-llm-key local-google-oidc local-oidc
local-trust:
sudo $(call sh_quote,$(PYTHON)) ci/agent-relay/kind/local_host_setup.py up
local-login: local-tools
PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py login
local-llm-key: local-tools
@PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py llm-key
local-google-oidc: local-tools
local-google-oidc local-oidc: local-tools
@PATH=$(call sh_quote,$(CURDIR)/.kind/tools):"$$PATH" $(call sh_quote,$(CURDIR)/.kind/tools/venv/bin/python3) ci/agent-relay/kind/local_stack.py google-oidc

.PHONY: local-postgres-cast-proof
Expand Down
56 changes: 42 additions & 14 deletions ci/agent-relay/kind/local_stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,8 @@ def values(self, phase, tenant=None):
if oidc:
# Real Google sign-in through Control's OIDC (the same code path as
# Okta or Entra ID); the email link stays as the operator fallback.
result["relay-control"]["auth"]["oidc"] = {"issuer": GOOGLE_ISSUER, "clientId": oidc["client_id"],
"allowedDomains": oidc["allowed_domains"], "displayName": "Google"}
result["relay-control"]["auth"]["oidc"] = {"issuer": oidc["issuer"], "clientId": oidc["client_id"],
"allowedDomains": oidc["allowed_domains"], "displayName": oidc["display_name"]}
# allowedDomains only gates who may authenticate; joining the single
# organization without an invite is auth.autoJoinDomains.
result["relay-control"]["auth"]["autoJoinDomains"] = oidc["allowed_domains"]
Expand Down Expand Up @@ -424,6 +424,10 @@ def values(self, phase, tenant=None):
for slot, producer in (("ingestEdge", "ingest"), ("nativeConsumer", "consumer"), ("sessionReadApi", "reader")):
result["sessions-pipeline"][slot]["analytics"] = analytics(producer)
worker = result["sessions-pipeline"]["worker"]
# The HoopDb owner login is local-pipeline-owner (this recipe runs the
# migrations); the kind-core profile's kind-pipeline Secret never
# exists here, and the chart's databaseGuard refuses a missing one.
worker.setdefault("migrations", {})["hoopdb"] = {"existingSecret": "local-pipeline-owner", "key": "url"}
worker.update(image=image(PIPELINE), existingSecret="local-brief", hoopdb={"existingSecret": "local-brief", "key": "HOOPDB_URL"},
postgresCa={"enabled": True, "configMap": "local-ca", "key": "ca.crt", "sha256": self.ca_sha},
locker={"endpoint": "http://locker.agent-relay.svc.cluster.local:9000", "bucket": "locker", "region": "us-east-1"},
Expand Down Expand Up @@ -464,17 +468,15 @@ def github_releases_egress(self):
"app.kubernetes.io/component": "api"}))

def google_oidc(self):
"""The Google OAuth client for local sign-in, or None (email link only)."""
"""The OIDC client for local sign-in, or None (email link only).

Google by default; an optional "issuer" (https) and "display_name"
select another provider, such as an Okta org, through the same file."""
state = getattr(self, "state", None)
path = state / "google-oidc.json" if state else None
if path is None or not path.exists():
return None
value = json.loads(path.read_text())
if not (isinstance(value.get("client_id"), str) and value["client_id"].endswith(".apps.googleusercontent.com")
and isinstance(value.get("client_secret"), str) and value["client_secret"]):
raise StackError(str(path) + " must hold a Google web client_id and client_secret")
value.setdefault("allowed_domains", ["agentrelay.com"])
return value
return oidc_client(json.loads(path.read_text()), str(path))

def google_oidc_egress(self):
selector = {"app.kubernetes.io/name": "relay-control", "app.kubernetes.io/instance": "agent-relay",
Expand All @@ -485,20 +487,22 @@ def google_oidc_egress(self):
self.k("delete", "networkpolicy", "local-control-oidc-egress", "--ignore-not-found=true")

def install_google_oidc(self):
"""Store a Google OAuth client (JSON on stdin) for this owned stack, then reconcile it."""
"""Store an OIDC client (JSON on stdin; Google unless it has "issuer") for this owned stack, then reconcile it."""
self.docker(require_space=False)
self.owned()
if sys.stdin.isatty():
raise StackError("pipe the client JSON on standard input; interactive entry would echo the secret")
raw = json.loads(sys.stdin.read())
domains = [d.strip() for d in os.environ.get("LOCAL_OIDC_ALLOWED_DOMAINS", "agentrelay.com").split(",") if d.strip()]
value = {"client_id": raw.get("client_id", ""), "client_secret": raw.get("client_secret", ""), "allowed_domains": domains}
value.update({k: raw[k] for k in ("issuer", "display_name") if raw.get(k)})
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
# Validate before replacing a working stored client.
label = oidc_client(dict(value), "the client JSON")["display_name"]
private_json(self.state / "google-oidc.json", value)
self.google_oidc() # validate before spending a reconcile
print("Google sign-in stored (0600; allowed domains: " + ", ".join(domains) + "). Reconciling the local stack...", flush=True)
print(label + " sign-in stored (0600; allowed domains: " + ", ".join(domains) + "). Reconciling the local stack...", flush=True)
self.up_local()
print("Register " + SITE + "/login/oidc/callback as an authorized redirect URI on that Google client, "
"then use 'Continue with Google' at " + SITE + "/login.")
print("Register " + SITE + "/login/oidc/callback as an authorized redirect URI on that client, "
"then use 'Continue with " + label + "' at " + SITE + "/login.")

def configure_model(self, key=None):
# Repeating local-up without an environment override preserves a key
Expand Down Expand Up @@ -877,6 +881,30 @@ def pgurl(role, credentials, ca, database="hoopdb"):
+ "?sslmode=verify-full" + ("&sslrootcert=" + ca if ca else ""))


def oidc_client(value, where):
"""Validate a stored OIDC client; Google unless it names an https issuer.

The issuer is kept exactly as given: Control compares it with the
provider's published issuer, which may end in "/". It must use the default
https port, the only one the local OIDC egress policy opens."""
issuer = value.get("issuer") or GOOGLE_ISSUER
label = r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
if not (isinstance(issuer, str)
and re.fullmatch(r"https://" + label + r"(?:\." + label + r")+(:443)?(/[^?#@\s]*)?", issuer)):
raise StackError(where + ": issuer must be an https URL on port 443, without query, fragment or credentials")
google = issuer.rstrip("/") == GOOGLE_ISSUER # either spelling gets Google's client-id check
if not (isinstance(value.get("client_id"), str) and value["client_id"]
and (not google or value["client_id"].endswith(".apps.googleusercontent.com"))
and isinstance(value.get("client_secret"), str) and value["client_secret"]):
raise StackError(where + " must hold a " + ("Google web " if google else "") + "client_id and client_secret")
if "display_name" in value and not (isinstance(value["display_name"], str) and value["display_name"].strip()):
raise StackError(where + ": display_name must be a non-empty string")
value["issuer"] = issuer
value.setdefault("display_name", "Google" if google else "single sign-on")
value.setdefault("allowed_domains", ["agentrelay.com"])
return value


def locker_env():
return [env("LOCKER_BUCKET", "locker"), env("LOCKER_ENDPOINT", "http://locker.agent-relay.svc.cluster.local:9000"),
env("LOCKER_REGION", "us-east-1"), env("ALLOW_IN_CLUSTER_HTTP", "true"),
Expand Down
48 changes: 47 additions & 1 deletion ci/agent-relay/kind/test_local_stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ def test_real_final_render_has_exact_core_roles_without_inline_credentials(self)
with patch.multiple(local_stack, DESKTOP_RELEASES=False, CONTROL=control, WEBAPP=webapp):
self.assert_final_render(experimental=False)

def test_google_oidc_renders_control_sign_in_and_egress_only_when_stored(self):
def test_oidc_renders_control_sign_in_and_egress_only_when_stored(self):
control, webapp = local_stack.profile_images(False)
with tempfile.TemporaryDirectory() as tmp, patch.multiple(local_stack, DESKTOP_RELEASES=False, CONTROL=control, WEBAPP=webapp):
stack = LocalStack.__new__(LocalStack)
Expand Down Expand Up @@ -566,6 +566,52 @@ def test_google_oidc_renders_control_sign_in_and_egress_only_when_stored(self):
(stack.state / "google-oidc.json").write_text(json.dumps({"client_id": "not-google", "client_secret": "x"}))
with self.assertRaises(local_stack.StackError):
stack.google_oidc()
# Any https issuer (an Okta org here) through the same file.
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
(stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://example.okta.com/",
"client_id": "0oaexample", "client_secret": "not-a-real-secret", "display_name": "Okta",
"allowed_domains": ["example.com"]}))
okta_values = stack.values("serve", tenant)
oidc = okta_values["relay-control"]["auth"]["oidc"]
# Kept exactly: Control compares it with the provider's published issuer.
self.assertEqual((oidc["issuer"], oidc["clientId"], oidc["displayName"]), ("https://example.okta.com/", "0oaexample", "Okta"))
result = subprocess.run(["helm", "template", "agent-relay", "charts/agent-relay", "-n", "agent-relay", "-f", "-", "--is-upgrade"],
cwd=ROOT, input=json.dumps(okta_values), capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("not-a-real-secret", result.stdout)
api = next(d for d in yaml.safe_load_all(result.stdout) if d and d["kind"] == "Deployment" and d["metadata"]["name"] == "relay-control")
names = {e["name"]: e.get("value") for c in api["spec"]["template"]["spec"]["containers"] for e in c.get("env", [])}
self.assertEqual((names["SELFHOST_OIDC_ISSUER"], names["SELFHOST_OIDC_CLIENT_ID"], names["SELFHOST_OIDC_DISPLAY_NAME"]),
("https://example.okta.com/", "0oaexample", "Okta"))
self.assertEqual(names["SELFHOST_OIDC_ALLOWED_DOMAINS"], "example.com")
self.assertIn("SELFHOST_OIDC_CLIENT_SECRET_FILE", names)
(stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://accounts.google.com/",
"client_id": "not-google", "client_secret": "x"}))
with self.assertRaises(local_stack.StackError):
stack.google_oidc() # Google's client-id check applies with a trailing slash too
(stack.state / "google-oidc.json").write_text(json.dumps({"issuer": "https://example.okta.com",
"client_id": "0oa", "client_secret": "x", "display_name": 7}))
with self.assertRaises(local_stack.StackError):
stack.google_oidc()
for bad in ("http://example.okta.com", "https://example.okta.com:8443", "https://u:p@example.okta.com",
"https://.okta.com", "https://example..okta.com", "https://-x.okta.com", "https://localhost"):
(stack.state / "google-oidc.json").write_text(json.dumps({"issuer": bad, "client_id": "0oaexample", "client_secret": "x"}))
with self.assertRaises(local_stack.StackError):
stack.google_oidc()

def test_oidc_install_rejects_bad_client_without_replacing_the_stored_one(self):
with tempfile.TemporaryDirectory() as tmp:
stack = LocalStack.__new__(LocalStack)
stack.state = Path(tmp)
stored = stack.state / "google-oidc.json"
good = {"client_id": "1-x.apps.googleusercontent.com", "client_secret": "kept", "allowed_domains": ["agentrelay.com"]}
stored.write_text(json.dumps(good))
bad = json.dumps({"issuer": "http://example.okta.com", "client_id": "0oa", "client_secret": "x"})
with patch.object(stack, "docker"), patch.object(stack, "owned"), patch.object(stack, "up_local") as up, \
patch.object(local_stack.sys, "stdin", io.StringIO(bad)):
with self.assertRaises(local_stack.StackError):
stack.install_google_oidc()
up.assert_not_called()
self.assertEqual(json.loads(stored.read_text()), good)

def test_google_oidc_secret_reconciles_when_control_bootstrap_is_cached(self):
with tempfile.TemporaryDirectory() as tmp:
Expand Down
Loading
Loading