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
104 changes: 104 additions & 0 deletions docs/conformance-v2.4.md

Large diffs are not rendered by default.

308 changes: 308 additions & 0 deletions tests/VellumPdf.Kernel.Tests/ConformanceAuditG6Support.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,308 @@
// Copyright © Timothy van der Ham (@Tim81)
// SPDX-License-Identifier: Apache-2.0

using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using VellumPdf.Document;
using VellumPdf.Forms;
using VellumPdf.Signing;
using static VellumPdf.Kernel.Tests.ConformanceAuditG1Support;
using Scan = VellumPdf.Kernel.Tests.AuditScanner;

namespace VellumPdf.Kernel.Tests;

/// <summary>
/// The forms audit (G6) reads a saved file with <see cref="AuditScanner"/>, which shares no code
/// with the writer: it reads the syntax of ISO 32000-1, clause 7, and keeps each token as written.
/// This class builds the fixtures (one document per field kind and per claim, and a document that
/// holds every kind) and the small readers over the scanned objects that the clause tests share.
/// </summary>
internal static class ConformanceAuditG6Support
{
internal static readonly byte[] PinnedId = Convert.FromHexString("000102030405060708090A0B0C0D0E0F");

internal static readonly PdfConformance[] Claims =
[PdfConformance.None, PdfConformance.PdfA2b, PdfConformance.PdfA2u, PdfConformance.PdfA2a, PdfConformance.PdfUA1];

internal static readonly PdfConformance[] ClaimsWithAnOracle =
[PdfConformance.PdfA2b, PdfConformance.PdfA2u, PdfConformance.PdfA2a, PdfConformance.PdfUA1];

/// <summary>The five kinds of field the Kernel builds, with the check box in both states.</summary>
internal enum Kind
{
Text,
CheckOn,
CheckOff,
Radio,
Combo,
List,
Push,
}

internal static readonly Kind[] AllKinds = Enum.GetValues<Kind>();

internal static string Flavour(PdfConformance claim) => claim switch
{
PdfConformance.PdfA2b => "2b",
PdfConformance.PdfA2u => "2u",
PdfConformance.PdfA2a => "2a",
PdfConformance.PdfUA1 => "ua1",
_ => throw new ArgumentOutOfRangeException(nameof(claim), claim, "No veraPDF flavour for this claim."),
};

// ── Documents ───────────────────────────────────────────────────────────────────────────

internal static PdfDocument NewDocument(PdfConformance claim)
{
var doc = new PdfDocument
{
Conformance = claim,
Timestamp = Pinned,
DocumentId = PinnedId,
Language = "en-US",
};
doc.Info.Title = "G6 audit";
return doc;
}

/// <summary>A rectangle 200 by 20 whose lower edge is <paramref name="y"/>.</summary>
internal static PdfRectangle Box(double y) => new(72, y, 272, y + 20);

/// <summary>Adds one field of <paramref name="kind"/> at <paramref name="y"/> with the values the tests read back.</summary>
internal static void AddField(PdfDocument doc, PdfPage page, Kind kind, double y)
{
switch (kind)
{
case Kind.Text:
doc.AddTextField(page, "text", Box(y), "Hello");
break;
case Kind.CheckOn:
doc.AddCheckBox(page, "checkOn", Box(y), true);
break;
case Kind.CheckOff:
doc.AddCheckBox(page, "checkOff", Box(y), false);
break;
case Kind.Radio:
doc.AddRadioButtonGroup(
"radio",
[new RadioOption(page, Box(y), "A"), new RadioOption(page, Box(y - 30), "B")],
"B");
break;
case Kind.Combo:
doc.AddChoiceField(page, "combo", Box(y), ["x", "y"], "y", combo: true);
break;
case Kind.List:
doc.AddChoiceField(page, "list", Box(y), ["x", "y"], "x", combo: false);
break;
case Kind.Push:
doc.AddPushButton(page, "push", Box(y), "Go");
break;
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
}
}

internal static PdfDocument FormDocument(PdfConformance claim, params Kind[] kinds)
{
var doc = NewDocument(claim);
var page = doc.AddPage();
var y = 700.0;
foreach (var kind in kinds)
{
AddField(doc, page, kind, y);
y -= 70;
}

return doc;
}

private static readonly ConcurrentDictionary<(PdfConformance, string), byte[]> FileCache = new();
private static readonly ConcurrentDictionary<(PdfConformance, string), Scan.Parsed> ParsedCache = new();

/// <summary>The saved file of a document that holds the given kinds, built once per run.</summary>
internal static byte[] FileBytes(PdfConformance claim, params Kind[] kinds) =>
FileCache.GetOrAdd((claim, string.Join(",", kinds)), _ => Save(FormDocument(claim, kinds)));

internal static Scan.Parsed Parsed(PdfConformance claim, params Kind[] kinds) =>
ParsedCache.GetOrAdd((claim, string.Join(",", kinds)), _ => Scan.Parse(FileBytes(claim, kinds)));

// ── Signing ─────────────────────────────────────────────────────────────────────────────

internal static readonly Lazy<X509Certificate2> Certificate = new(() =>
{
using var rsa = RSA.Create(2048);
var request = new CertificateRequest("CN=VellumPdf audit", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return request.CreateSelfSigned(Pinned.AddDays(-1), Pinned.AddYears(1));
});

internal static byte[] Signed(PdfConformance claim, bool withFields, PadesLevel level = PadesLevel.B_B)
{
var doc = withFields ? FormDocument(claim, AllKinds) : FormDocument(claim);
using var ms = new MemoryStream();
doc.Sign(ms, new PdfSignatureSettings
{
Certificate = Certificate.Value,
SigningTime = Pinned,
Level = level,
TimestampClient = level >= PadesLevel.B_T ? new TestTimestampClient(Pinned) : null,
RevocationClient = level >= PadesLevel.B_LT ? new CannedRevocation() : null,
});
return ms.ToArray();
}

private sealed class CannedRevocation : IRevocationClient
{
public RevocationData GetRevocationData(X509Certificate2 certificate, X509Certificate2 issuer)
=> new()
{
Ocsp = new ReadOnlyMemory<byte>([0x30, 0x03, 0x0A, 0x01, 0x00]),
Crl = new ReadOnlyMemory<byte>([0x30, 0x04, 0x02, 0x01, 0x2A]),
};
}

// ── Readers over a scanned file ─────────────────────────────────────────────────────────

internal static Scan.PDict Dict(this Scan.Parsed p, object? value) =>
Assert.IsType<Scan.PDict>(p.Resolve(value));

internal static List<object?> Arr(this Scan.Parsed p, object? value) =>
Assert.IsType<List<object?>>(p.Resolve(value));

internal static Scan.PDict AcroForm(this Scan.Parsed p) => p.Dict(p.Catalog["AcroForm"]);

/// <summary>The objects of the document's <c>/Fields</c> array, in order.</summary>
internal static List<Scan.Obj> RootFields(this Scan.Parsed p) =>
[.. p.Arr(p.AcroForm()["Fields"]).Select(r => p.Get(Assert.IsType<Scan.PRef>(r).Number))];

/// <summary>Every widget annotation object in the file, in object order.</summary>
internal static List<Scan.Obj> Widgets(this Scan.Parsed p) =>
[.. p.Objects.Where(o => o.Dict?.Name("Subtype") == "Widget")];

/// <summary>The widgets a page lists in its <c>/Annots</c>, by page index.</summary>
internal static List<Scan.Obj> PageAnnots(this Scan.Parsed p, int pageIndex)
{
var page = p.Objects.Where(o => o.Dict?.Name("Type") == "Page").ElementAt(pageIndex);
return page.Dict!["Annots"] is null
? []
: [.. p.Arr(page.Dict["Annots"]).Select(r => p.Get(Assert.IsType<Scan.PRef>(r).Number))];
}

internal static Scan.Obj Page(this Scan.Parsed p, int pageIndex) =>
p.Objects.Where(o => o.Dict?.Name("Type") == "Page").ElementAt(pageIndex);

/// <summary>The widget or field dictionary whose <c>/T</c> is <paramref name="name"/>.</summary>
internal static Scan.Obj FieldNamed(this Scan.Parsed p, string name) =>
p.Objects.Single(o => o.Dict?["T"] is Scan.PStr s && Decode(s) == name);

/// <summary>A text string as a reader decodes it (7.9.2.2): UTF-16BE after a byte order mark, else Latin-1.</summary>
internal static string Decode(Scan.PStr s)
{
var b = s.Bytes;
return b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF
? Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2)
: Encoding.Latin1.GetString(b);
}

internal static double Num(object? value) =>
double.Parse(Assert.IsType<Scan.PNum>(value).Raw, CultureInfo.InvariantCulture);

internal static double[] Nums(this Scan.Parsed p, object? array) =>
[.. p.Arr(array).Select(Num)];

/// <summary>The decoded bytes of a stream object.</summary>
internal static byte[] StreamBytes(Scan.Obj stream) =>
stream.Dict!.Name("Filter") == "FlateDecode" ? Scan.Inflate(stream.StreamData!) : stream.StreamData!;

/// <summary>The tokens of a content stream as written: names, numbers, strings and operator keywords.</summary>
internal static List<object> Content(Scan.Obj stream)
{
var lex = new Scan.Lexer(StreamBytes(stream), 0);
var tokens = new List<object>();
while (true)
{
lex.SkipWs();
if (lex.AtEnd)
break;
tokens.Add(lex.ReadToken());
}

return tokens;
}

/// <summary>The operator keywords of a content stream, in order.</summary>
internal static List<string> Operators(Scan.Obj stream) =>
[.. Content(stream).OfType<Scan.PKeyword>().Select(k => k.Text)];

/// <summary>The font names and sizes the Tf operators of a content stream select, in order.</summary>
internal static List<(string Font, double Size)> FontsSelected(Scan.Obj stream)
{
var tokens = Content(stream);
var result = new List<(string, double)>();
for (var i = 2; i < tokens.Count; i++)
{
if (tokens[i] is Scan.PKeyword { Text: "Tf" })
result.Add((Assert.IsType<Scan.PName>(tokens[i - 2]).Text, Num(tokens[i - 1])));
}

return result;
}

/// <summary>The strings the Tj operators of a content stream show, as bytes.</summary>
internal static List<byte[]> ShownStrings(Scan.Obj stream)
{
var tokens = Content(stream);
var result = new List<byte[]>();
for (var i = 1; i < tokens.Count; i++)
{
if (tokens[i] is Scan.PKeyword { Text: "Tj" })
result.Add(Assert.IsType<Scan.PStr>(tokens[i - 1]).Bytes);
}

return result;
}

/// <summary>
/// Whether <paramref name="value"/> is an indirect reference to a stream. The scanner keeps a stream
/// object's dictionary as its value, so resolving the reference alone does not tell a stream from a dictionary.
/// </summary>
internal static bool IsStream(Scan.Parsed p, object? value) =>
value is Scan.PRef r && p.Get(r.Number).StreamData is not null;

/// <summary>The normal appearance streams of a widget: one for a stream, one per state for a subdictionary.</summary>
internal static Dictionary<string, Scan.Obj> NormalAppearances(Scan.Parsed p, Scan.PDict widget)
{
var n = p.Dict(widget["AP"])["N"];
var result = new Dictionary<string, Scan.Obj>();
if (IsStream(p, n))
{
result[""] = p.Get(((Scan.PRef)n!).Number);
return result;
}

foreach (var (key, value) in p.Dict(n).Entries)
result[key] = p.Get(Assert.IsType<Scan.PRef>(value).Number);
return result;
}

internal static Scan.PDict InheritedFieldType(Scan.Parsed p, Scan.PDict widget)
{
var current = widget;
while (current["FT"] is null && current["Parent"] is { } parent)
current = p.Dict(parent);
return current;
}

internal static bool UsesZapfDingbats(Kind kind) => kind is Kind.CheckOn or Kind.CheckOff or Kind.Radio;

// ── The veraPDF verdict of each fixture, as the rules veraPDF 1.30.4 gives them ────────

/// <summary>
/// The failed rules of <paramref name="bytes"/> as <c>clause-test</c>, sorted and without repeats, so a pin
/// reads the same whichever order veraPDF reports them in.
/// </summary>
internal static string[] Failed(PdfConformance claim, byte[] bytes) =>
[.. VeraPdfFailures(Flavour(claim), bytes).Distinct().Order(StringComparer.Ordinal)];
}
Loading
Loading