Skip to content
Open
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
5 changes: 5 additions & 0 deletions azure-pipelines/pull-request-validation/common4j.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ stages:
tasks: common4j:jacocoTestReport flight-governance:test flight-governance:installDist -Psugar=true -PmockApiUrl=$(MOCK_API_URL) -PnativeAuthConfigString=$(NATIVE_AUTH_CONFIG_STRING)
javaHomeOption: JDKVersion
jdkVersionOption: 1.17
- template: ../templates/steps/flight-governance.yml
parameters:
repositoryLabel: common
sourcePaths:
- common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java
- script: tree "$(Build.SourcesDirectory)" /F /A
displayName: 'Print File Structure Tree'
- publish: $(Build.SourcesDirectory)/common4j/build/reports/jacoco/test/jacocoTestReport.xml
Expand Down
79 changes: 79 additions & 0 deletions azure-pipelines/templates/steps/flight-governance.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

parameters:
- name: repositoryRoot
type: string
default: $(Build.SourcesDirectory)
- name: toolingRoot
type: string
default: $(Build.SourcesDirectory)
- name: repositoryLabel
type: string
- name: sourcePaths
type: object
- name: policyPath
type: string
default: config/flight-governance.json
- name: reportDirectory
type: string
default: $(Build.ArtifactStagingDirectory)/flight-governance
- name: artifactName
type: string
default: flight-governance

steps:
- pwsh: |
$ErrorActionPreference = 'Stop'
$env:JAVA_HOME = $env:GOV_JAVA_HOME
New-Item -ItemType Directory -Path $env:GOV_REPORT_DIRECTORY -Force | Out-Null
$target = $env:SYSTEM_PULLREQUEST_TARGETBRANCH -replace '^refs/heads/', ''
$source = $env:SYSTEM_PULLREQUEST_SOURCECOMMITID
if ($source -notmatch '^[0-9a-f]{40,64}$' -or [string]::IsNullOrWhiteSpace($target)) {
throw 'PR source commit and target branch are required; do not substitute the generated merge commit.'
}
git -C $env:GOV_REPOSITORY check-ref-format --branch $target
if ($LASTEXITCODE -ne 0) { throw 'Invalid PR target branch.' }
$shallow = git -C $env:GOV_REPOSITORY rev-parse --is-shallow-repository
if ($LASTEXITCODE -ne 0) { throw 'Cannot inspect repository history.' }
if ($shallow -eq 'true') {
git -C $env:GOV_REPOSITORY fetch --no-tags --unshallow origin
if ($LASTEXITCODE -ne 0) { throw 'Cannot obtain full merge-base and trusted-baseline history.' }
}
git -C $env:GOV_REPOSITORY fetch --no-tags origin "+refs/heads/${target}:refs/remotes/origin/$target"
if ($LASTEXITCODE -ne 0) { throw 'Cannot fetch the PR target.' }
git -C $env:GOV_REPOSITORY fetch --no-tags origin $source
if ($LASTEXITCODE -ne 0) { throw 'Cannot fetch the PR source commit.' }
$report = Join-Path $env:GOV_REPORT_DIRECTORY 'report.json'
$toolName = if ($IsWindows) { 'flight-governance.bat' } else { 'flight-governance' }
$tool = Join-Path $env:GOV_TOOLING "tooling/flight-governance/build/install/flight-governance/bin/$toolName"
$arguments = @('check-pr', '--repository', $env:GOV_LABEL, $env:GOV_REPOSITORY,
'--base', "refs/remotes/origin/$target", '--head', $source,
'--policy', $env:GOV_POLICY, '--output', $report)
foreach ($path in ($env:GOV_SOURCE_PATHS | ConvertFrom-Json)) {
$arguments += @('--source', $path)
}
& $tool @arguments
if ($LASTEXITCODE -ne 0) { throw 'Flight governance scan is incomplete; see the report and task log.' }
$result = Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
if ($result.status -ne 'complete') { throw 'The scan did not produce a complete report.' }
if ($result.findings.Count -gt 0) {
Write-Host "##vso[task.logissue type=warning]Flight governance: $($result.findings.Count) advisory findings; see the attached report."
}
Write-Host "##vso[task.uploadsummary]$report.md"
displayName: Report flight governance (non-blocking policy findings)
condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
env:
GOV_REPOSITORY: ${{ parameters.repositoryRoot }}
GOV_TOOLING: ${{ parameters.toolingRoot }}
GOV_LABEL: ${{ parameters.repositoryLabel }}
GOV_SOURCE_PATHS: ${{ convertToJson(parameters.sourcePaths) }}
GOV_POLICY: ${{ parameters.policyPath }}
GOV_REPORT_DIRECTORY: ${{ parameters.reportDirectory }}
GOV_JAVA_HOME: $(JAVA_HOME_17_X64)
- task: PublishPipelineArtifact@1
displayName: Publish flight-governance report
condition: and(succeededOrFailed(), eq(variables['Build.Reason'], 'PullRequest'))
inputs:
targetPath: ${{ parameters.reportDirectory }}
artifact: ${{ parameters.artifactName }}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ package com.microsoft.identity.common.java.flighting
*
* Completeness and premortem requirements are enforced by development tooling, not this annotation.
*
* @property owner Accountable person or team. Empty permits a tooling-resolved ownership candidate;
* git authorship alone does not confirm current ownership.
* @property owner Explicit accountable current person or team. The empty default preserves source
* compatibility but does not satisfy governance checks for new or changed declarations.
* @property type Intended lifecycle of the flight.
* @property premortem Repository-relative premortem path. Required by policy for new or materially
* changed release flights, regardless of their default value.
* @property premortem Repository-relative governance document path, retaining the original field
* name. Required for new or materially changed flights of every type, regardless of default value;
* approved initial legacy backfill may retain a recorded historical document gap.
*/
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.BINARY)
Expand Down
5 changes: 5 additions & 0 deletions config/flight-governance.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"_copyright": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.",
"schemaVersion": 1,
"legacyRevision": "aea799488d50b487381548fdd5bb5cd68d3375e9"
}
6 changes: 5 additions & 1 deletion docs/premortem/_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<!-- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. -->

# Premortem: <flight or change>
# Flight governance document: <flight or change>

Required for new or materially changed flights of every type. Link this document
using `FlightMeta.premortem`; that field name is retained for compatibility.
Historical document gaps are accepted for approved initial legacy metadata backfill.

## Ownership and scope

Expand Down
72 changes: 72 additions & 0 deletions tooling/flight-governance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,75 @@ destination or a destination inside an input repository. This prevents accidenta
overwrite; it is not a digital signature or filesystem immutability guarantee.
Review the candidate and store the approved snapshot in controlled, versioned storage
before treating it as a trusted legacy baseline. This tool cannot approve it.

## Report-only PR checks

After building the distribution, invoke the checker with the real PR source revision
and target branch, not the generated PR merge commit:

```powershell
.\tooling\flight-governance\build\install\flight-governance\bin\flight-governance.bat check-pr `
--repository common C:\src\common --base origin/dev --head <source-commit> `
--source common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java `
--policy config/flight-governance.json --output C:\temp\flight-pr-report.json
```

`check-pr` paths are Git paths using `/` separators. Repeat `--source` for additional
registries. Full history and a single target merge base are required. The checkout
is read-only; reports must be new files outside it. JSON and a `.json.md` summary
identify the source, target, merge base, evaluated declarations, findings and initial
legacy gaps. Policy findings return zero during this pilot; failed or incomplete
execution returns nonzero and, when the destination is valid, an incomplete JSON report.
Complete JSON is published only after its Markdown summary is written; a failed scan
may have no Markdown summary. Existing destination entries, including dangling
symlinks, are never overwritten.

New/changed keys, defaults or metadata need an explicit current person/team owner
and lifecycle type. Git authorship never substitutes for ownership; reviewers confirm
that the recorded owner is current. Every type (Release, Kill Switch and Config)
requires an existing same-repository Markdown governance document regardless of default.
The path uses `FlightMeta.premortem`, whose name is retained for compatibility.
Changing type does not evade the document requirement. Untouched
legacy declarations and formatting/comments alone are grandfathered. Removing or
renaming a linked document is reported even without an enum edit.

The policy engine consumes normalized records; the Java adapter handles syntax.
It has no hardcoded registry paths or Broker precedence. Future Kotlin extraction
can feed the same policy model, but is not implemented here.

### Trusted initial legacy migration

The checker reads `--policy` only from the resolved **target commit**. Missing policy
means no exceptions, not an empty successful policy evaluation. The initial committed
policy freezes the pre-policy baseline. The baseline must belong to the target's
history; the PR source may have branched before it.

```json
{
"schemaVersion": 1,
"legacyRevision": "<full-pre-policy-commit-id>"
}
```

Only the initial metadata addition to an unannotated legacy declaration qualifies.
The same declaration, key and default must exist without metadata at the frozen
baseline, PR merge base and current target. Its owner must be explicit, its type
supported, and its metadata resolvable. Reviewers validate owner/type in the same
backfill PR; no separate approval PR or per-flight approval list is required.

The PR cannot contain runtime changes. The adapter compares Java syntax after
removing governance metadata/imports; other changed files must be Markdown under
`docs/`. Prefer explicit metadata imports for migration PRs. PR-authored baseline
edits cannot grant an exception. Unknown owners, new keys, changed defaults,
reclassification and later metadata edits do not qualify, including on branches
forked before the first backfill. Historical document gaps stay visible in the report
instead of becoming missing-document findings or fabricated documents.

The shared ADO step fetches the PR source/target and publishes advisory findings;
incomplete scans fail explicitly. This is checkpoint A only: it changes neither
branch policies nor the eventual blocking policy mode. Reviewers must still identify
material behavior changes elsewhere that declaration comparisons cannot infer.

This repository-governance check is separate from the planned monthly, user-invoked
audit skill for old flights and configuration discrepancies. That later skill is not
a prerequisite for metadata backfill or PR enforcement and is not a release gate.
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.identity.tools.flightgovernance

internal data class PolicyMetadata(
val owner: String = "",
val type: String = "",
val premortem: String = "",
val invalidArguments: Set<String> = emptySet()
)

internal data class PolicyDeclaration(
val id: String,
val path: String,
val line: Long,
val key: String,
val defaultExpression: String,
val metadata: PolicyMetadata?
) {
fun sameBehavior(other: PolicyDeclaration): Boolean =
key == other.key && defaultExpression == other.defaultExpression
}

internal data class PolicyInputs(
val before: List<PolicyDeclaration>,
val after: List<PolicyDeclaration>,
val beforeFiles: Set<String>,
val afterFiles: Set<String>,
val legacy: List<PolicyDeclaration> = emptyList(),
val metadataOnly: Boolean = false,
val target: List<PolicyDeclaration> = before
)

internal data class PolicyFinding(
val rule: String,
val declaration: PolicyDeclaration,
val message: String,
val fix: String
)

internal data class PolicyResult(
val findings: List<PolicyFinding>,
val checked: List<String>,
val legacyDocumentGaps: List<String>
)

/** Evaluates normalized declarations; language extraction and Git access belong to adapters. */
internal object FlightPolicy {
private val supportedTypes = setOf("RELEASE", "KILL_SWITCH", "CONFIG")

fun evaluate(input: PolicyInputs): PolicyResult {
require(input.before.map { it.id }.distinct().size == input.before.size) { "Duplicate old declaration" }
require(input.after.map { it.id }.distinct().size == input.after.size) { "Duplicate new declaration" }
require(input.target.map { it.id }.distinct().size == input.target.size) { "Duplicate target declaration" }
val before = input.before.associateBy { it.id }
val legacy = input.legacy.associateBy { it.id }
val target = input.target.associateBy { it.id }
val findings = mutableListOf<PolicyFinding>()
val checked = mutableListOf<String>()
val gaps = mutableListOf<String>()
for (flight in input.after.sortedBy { it.id }) {
val old = before[flight.id]
val metadata = flight.metadata
fun finding(rule: String, message: String, fix: String) {
findings.add(PolicyFinding(rule, flight, message, fix))
}
val brokenLink = old?.metadata?.premortem?.takeIf { it.isNotBlank() }?.let {
it == metadata?.premortem && it in input.beforeFiles && it !in input.afterFiles
} == true
if (brokenLink) {
finding("BROKEN_DOCUMENT", "Previously linked governance document was removed or renamed.",
"Restore the document or update the flight's document link.")
}
if (old != null && old.sameBehavior(flight) && old.metadata == metadata) {
continue
}
checked.add(flight.id)
if (metadata == null) {
finding("MISSING_METADATA", "Added or modified flight has no governance metadata.",
"Add an explicit owner, lifecycle type and linked governance document.")
continue
}
if (metadata.invalidArguments.isNotEmpty()) {
finding("UNRESOLVED_METADATA", "Unsupported metadata arguments: ${metadata.invalidArguments.sorted()}.",
"Use literal owner/document values and a supported lifecycle type.")
}
if (metadata.type !in supportedTypes) {
finding("MISSING_TYPE", "A supported lifecycle type is required.",
"Classify the flight as RELEASE, KILL_SWITCH or CONFIG.")
}
if (metadata.owner.isBlank()) {
finding("MISSING_OWNER", "An explicit accountable owner is required.",
"Record a current person/team; Git authorship does not satisfy ownership.")
}
val initialLegacyBackfill = input.metadataOnly &&
listOf(old, legacy[flight.id], target[flight.id]).all {
it != null && it.metadata == null && it.sameBehavior(flight)
} &&
metadata.owner.isNotBlank() && metadata.type in supportedTypes &&
metadata.invalidArguments.isEmpty()
if (!brokenLink) {
if (metadata.premortem.isBlank() && initialLegacyBackfill) {
gaps.add(flight.id)
} else if (!repositoryPath(metadata.premortem) ||
!metadata.premortem.endsWith(".md", ignoreCase = true) ||
metadata.premortem !in input.afterFiles
) {
finding("MISSING_DOCUMENT", "Every flight type requires an existing same-repository Markdown document.",
"Link an existing governance document; only initial metadata-only legacy backfill may record a historical gap.")
}
}
}
return PolicyResult(findings, checked, gaps)
}
}

internal fun repositoryPath(path: String): Boolean =
path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\\' !in path &&
path.split('/').none { it in setOf("", ".", "..") }
Loading
Loading