blob: 6511b5d5b14fc8057600eedd11deb7da5c6818ce [file]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Defines the canonical runtime environment contract for build authentication."""
import enum
import functools
import os
from collections.abc import Mapping
from pathlib import Path
# Canonical environment variable names for build-level authentication.
ENV_RBE_AUTH_TYPE = "FX_BUILD_RBE_AUTH_TYPE"
ENV_RS_AUTH_TYPE = "FX_BUILD_RS_AUTH_TYPE"
ENV_GOOGLE_APPLICATION_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS"
ENV_USER = "USER"
# LINT.IfChange(build_auth_config)
_BUILD_AUTH_CONFIG = Path(".fx/config/build-auth")
# LINT.ThenChange(//tools/devshell/rbe:build_auth_config)
class AuthType(str, enum.Enum):
"""Supported authentication methods across Fuchsia build tools."""
LOAS = "loas"
OAUTH = "oauth"
MACHINE = "machine"
NONE = "none"
AUTO = "auto"
def __str__(self) -> str:
return self.value
# Top-level aliases for convenient access.
LOAS = AuthType.LOAS
OAUTH = AuthType.OAUTH
MACHINE = AuthType.MACHINE
NONE = AuthType.NONE
AUTO = AuthType.AUTO
def make_auth_env(
rbe_auth: str | AuthType = AuthType.NONE,
rs_auth: str | AuthType = AuthType.NONE,
user: str | None = None,
credentials_file: Path | str | None = None,
) -> dict[str, str]:
"""Constructs a clean dictionary of build authentication environment variables."""
env: dict[str, str] = {
ENV_RBE_AUTH_TYPE: str(rbe_auth),
ENV_RS_AUTH_TYPE: str(rs_auth),
}
if user is not None:
env[ENV_USER] = user
if credentials_file is not None:
env[ENV_GOOGLE_APPLICATION_CREDENTIALS] = str(credentials_file)
return env
def rbe_auth_type(env: Mapping[str, str]) -> str:
"""Returns the RBE auth type, defaulting to 'none'."""
return env.get(ENV_RBE_AUTH_TYPE, AuthType.NONE.value)
def rs_auth_type(env: Mapping[str, str]) -> str:
"""Returns the ResultStore auth type, defaulting to 'none'."""
return env.get(ENV_RS_AUTH_TYPE, AuthType.NONE.value)
def is_loas(env: Mapping[str, str]) -> bool:
"""True if either RBE or ResultStore is configured to use LOAS."""
return AuthType.LOAS.value in (rbe_auth_type(env), rs_auth_type(env))
def requires_gcert(env: Mapping[str, str]) -> bool:
"""Semantic alias for is_loas; True if corporate gcert is required."""
return is_loas(env)
def credentials_file(env: Mapping[str, str]) -> Path | None:
"""Returns the path to GOOGLE_APPLICATION_CREDENTIALS if set."""
path = env.get(ENV_GOOGLE_APPLICATION_CREDENTIALS)
return Path(path) if path else None
def reclient_credshelper_path(fuchsia_dir: Path, host_tag: str) -> Path:
"""Returns the canonical path to the prebuilt reclient credshelper binary."""
return (
fuchsia_dir
/ "prebuilt"
/ "third_party"
/ "reclient"
/ host_tag
/ "credshelper"
)
def cached_auth_type(fuchsia_dir: Path) -> str | None:
"""Returns the auth type that `fx rbe` caches in .fx/config/build-auth."""
# TODO(https://fxbug.dev/573624782): Use //build/scripts:properties_lib
# once it has a Bazel target.
try:
text = (fuchsia_dir / _BUILD_AUTH_CONFIG).read_text(errors="replace")
except OSError:
return None
for line in text.splitlines():
key, _, value = line.partition("#")[0].partition("=")
value = value.strip().strip("'\"")
if key.strip() == "auth_type" and value:
return value
return None
def _probe_system_auth_type(
env: Mapping[str, str],
fuchsia_dir: Path | None = None,
) -> AuthType:
from build.auth import select_auth_method
root = fuchsia_dir or Path(__file__).resolve().parent.parent.parent
check_loas_script = root / "build/auth/check_loas_restrictions.sh"
try:
detected = select_auth_method.select_auth_method(
env=dict(env),
check_loas_script=check_loas_script,
)
return AuthType(detected.value)
except ValueError as err:
raise RuntimeError(
f"Unable to infer build authentication type: {err}"
) from err
@functools.cache
def detect_system_auth_type(
fuchsia_dir: Path | None = None,
) -> AuthType:
"""Probes the host system to determine the appropriate authentication type.
Cached in-process to avoid redundant gcertstatus and gcloud subprocess invocations.
"""
return _probe_system_auth_type(os.environ, fuchsia_dir)
def resolve_build_auth_type(
auth_type: str | AuthType = AuthType.AUTO,
use_machine_credentials: bool = False,
env: Mapping[str, str] | None = None,
fuchsia_dir: Path | None = None,
service_env_var: str = ENV_RBE_AUTH_TYPE,
) -> str:
"""Resolves effective build authentication type (loas, oauth, machine, none).
Precedence:
1. use_machine_credentials -> machine
2. auth_type != 'auto' -> explicit auth_type
3. env.get(service_env_var) -> inherited parent wrapper environment
4. cached_auth_type() -> auth type cached by `fx rbe`
5. detect_system_auth_type() -> host system detection (cached when env is None)
"""
if use_machine_credentials:
return AuthType.MACHINE.value
active_env = os.environ if env is None else env
resolved = str(auth_type)
if resolved == AuthType.AUTO.value:
env_auth = active_env.get(service_env_var)
if env_auth and env_auth != AuthType.AUTO.value:
resolved = env_auth
if resolved == AuthType.AUTO.value and fuchsia_dir:
resolved = cached_auth_type(fuchsia_dir) or resolved
if resolved == AuthType.AUTO.value:
if env is None:
detected = detect_system_auth_type(fuchsia_dir)
else:
detected = _probe_system_auth_type(env, fuchsia_dir)
resolved = str(detected)
valid_types = {t.value for t in AuthType if t != AuthType.AUTO}
if resolved not in valid_types:
raise ValueError(f"Unhandled authentication type: {resolved!r}")
return resolved