Skip to content

Koruma doğruluğu düzeltmeleri, güven ağı, dokümantasyon ve CI - #2

Open
saracmert wants to merge 2 commits into
mainfrom
claude/project-analysis-features-9o0qmw
Open

saracmert wants to merge 2 commits into
mainfrom
claude/project-analysis-features-9o0qmw

Conversation

@saracmert

Copy link
Copy Markdown
Member

Özet

Bu PR, kod analizinde tespit edilen ve varsayılan yapılandırmada PII korumasını sessizce devre dışı bırakan hataları giderir, bir test/güven ağı ekler, kapsamlı dokümantasyon getirir ve testleri CI'a entegre eder. (Analiz raporundaki yol haritasının 1. ve 2. maddeleri.)

CI (.NET CI) bu dalda çalıştı: build 0 uyarı/0 hata, 42/42 test geçti, coverage + trx artifact olarak yüklendi.

Korumayı gerçekten çalışır kılan düzeltmeler

  • IBAN tip anahtarı uyumsuzluğu giderildi. Tanıyıcı IBAN üretirken Weights/RedactTypes IBAN_TR bekliyordu; IBAN ağırlık 1 alıyor ve hiç redakte edilmiyordu. Tüm tip anahtarları tek kaynakta (PiiTypes) birleştirildi.
  • TCKN artık dilden bağımsız tespit edilir (checksum yeterli); Türkçe diakritik içermeyen ASCII gövdelerde de bulunur.
  • Telefon ulusal formatı (05xx…) DefaultPhoneRegion/dil bölgesiyle ayrıştırılır (eski "ZZ" her seferinde istisna fırlatıyordu).
  • IBAN boşluklu (4'lü gruplu) gösterimi tanınır.
  • Adres anahtar sözcükleri kelime sınırıyla eşleşir (have→ave, katalog→kat yanlış pozitifleri giderildi).
  • DOB takvim + gelecek doğrulaması; kredi kartı regex düzeltmesi + Troy/Discover/JCB/Maestro/Diners ve 13/19 haneli Visa.
  • Tüm regex tanıyıcılarına ReDoS'a karşı MatchTimeout; güvenli e-posta deseni.

Middleware / HTTP

  • Yanıt gövdesi swap'ı try/finally ile korunur (downstream istisnada orijinal stream geri yüklenir).
  • Block modunda 403 gövdesi istemciye ulaşır; -Detected header'ları bloklanan yanıtta temizlenir (oracle önlenir).
  • Redaksiyon sonrası Content-Length güncellenir (Kestrel uyuşmazlık hatası giderildi).
  • ResponseCaptureStream: yalnızca analiz edilebilir içerik türleri ve MaxBodySizeBytes'a kadar tamponlanır; büyük/streaming (SSE) yanıtlar doğrudan akıtılır (OOM ve streaming bozulması giderildi).
  • İstek gövdesi boyut sınırı; UTF-8 dışı charset koruması; culture-invariant risk header'ı; metod filtreleri büyük/küçük harf duyarsız.

Motor / Options / DI / Edge

  • Skorlamada çakışma (overlap) çözümü, risk clamp(0,10), açık 0 ağırlığı tipi devre dışı bırakır, entity filtreleri NER hit'lerine de uygulanır.
  • DataGuardianOptions.Validate() ve başlangıçta doğrulama.
  • AddDataGuardian(IConfiguration/Action) + UseDataGuardian overload'ları (DI + konfigürasyon bağlama).
  • Edge snippet: fail-closed seçeneği, NaN/eksik header ve virgüllü ondalık toleransı.

Güven ağı ve CI

  • xUnit + Microsoft.AspNetCore.TestHost ile recognizer/engine/middleware/options testleri (42 test). Her düzeltilen hata için bir regresyon kilidi.
  • CI feature dallarında da çalışır; trx + coverage artifact yükler.
  • Dependabot kapsamı: NuGet / + github-actions. Kullanılmayan Google.Protobuf bağımlılığı kaldırıldı.

Dokümantasyon

  • docs/ (configuration, recognizers, scoring, actions, security, edge, contributing), CHANGELOG.md, güncellenmiş README, genel API'lerde XML doc yorumları.

⚠️ Davranış değişikliği (migrasyon)

appsettings içinde Weights/RedactTypes için IBAN_TR kullananlar IBAN olarak güncellemelidir. Ayrıntı CHANGELOG.md'de.

Kapsam dışı (Roadmap v2/v3)

NER'in derin sorunları (token→karakter ofset eşlemesi, tokenizer API bağlaması, dinamik ONNX girdileri, pencereleme) bu PR'da ele alınmadı; NER v1.x'te skor/etiketleme için işaretlendi, redaksiyon için önerilmiyor (docs/recognizers.md).

🤖 Generated with Claude Code


Generated by Claude Code

Roadmap 1 & 2: korumayı gerçekten çalışır kılan düzeltmeler + güven ağı.

Recognizer/engine:
- Tip anahtarlarını tek kaynakta topla (PiiTypes); IBAN "IBAN_TR"
  uyumsuzluğunu gider (artık skorlanır ve redakte edilir)
- TCKN dil kapısını kaldır (checksum yeterli); ASCII gövdelerde de bulunur
- PhoneRecognizer ulusal formatı bölgeyle ayrıştırır (05xx... tespit edilir)
- IBAN boşluklu (4'lü gruplu) gösterimi tanır
- Adres anahtar sözcüklerini kelime sınırıyla eşle (yanlış pozitif giderildi)
- DOB takvim + gelecek doğrulaması; kredi kartı regex + Troy/Discover/JCB/
  Maestro/Diners ve 13/19 haneli Visa
- Regex ReDoS: MatchTimeout + güvenli e-posta deseni
- Engine: çakışma çözümü, risk clamp, açık 0 ağırlığı, filtreler NER'e de

Middleware:
- Body swap'ı try/finally ile koru; block gövdesi istemciye ulaşır ve
  detection header'ları temizlenir
- Redaksiyon sonrası Content-Length güncelle
- ResponseCaptureStream: yalnızca analiz edilebilir tipleri ve boyut sınırına
  kadar tamponla; büyük/streaming yanıtları doğrudan akıt (OOM/SSE giderildi)
- İstek gövdesi boyut sınırı; charset kontrolü; culture-invariant header;
  metod filtresi büyük/küçük harf duyarsız

Options/DI/edge:
- DataGuardianOptions.Validate() ve başlangıçta doğrulama
- AddDataGuardian(IConfiguration/Action) + UseDataGuardian overload'ları
- Edge snippet: fail-closed seçeneği, NaN/eksik header ve virgül ondalık

Güven ağı ve CI:
- xUnit + TestHost ile recognizer/engine/middleware/options testleri
- CI feature dallarında da çalışır; trx + coverage artifact
- Dependabot NuGet "/" + github-actions; kullanılmayan Google.Protobuf kaldırıldı

Dokümantasyon:
- docs/ (configuration, recognizers, scoring, actions, security, edge,
  contributing), CHANGELOG.md, README güncellendi, XML doc yorumları

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EQCGkU1zZXK3oCoAxPgCzf
Copilot AI review requested due to automatic review settings July 16, 2026 22:14

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Bu PR, DataGuardian’ın PII tespit/sınıflandırma doğruluğunu ve güvenliğini artırmayı, middleware’in HTTP davranışlarını daha güvenilir hale getirmeyi, kapsamlı test/dokümantasyon eklemeyi ve CI/Dependabot entegrasyonunu güçlendirmeyi hedefliyor.

Changes:

  • Tanıyıcılarda doğruluk + güvenlik iyileştirmeleri (tip anahtarlarını PiiTypes ile birleştirme, regex timeout/ReDoS koruması, IBAN/telefon/TCKN/DOB/kredi kartı düzeltmeleri).
  • Middleware’de güvenilir request/response analiz-redaksiyon-blok akışı (stream swap try/finally, body size/charset/content-type kontrolleri, Content-Length düzeltmeleri, header davranışları).
  • xUnit + TestHost test paketi, docs/ dokümantasyonu, CI’de test/coverage artifact’ları ve Dependabot kapsamı.

Reviewed changes

Copilot reviewed 34 out of 34 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/Devoplus.DataGuardian.Tests/RecognizerTests.cs Tanıyıcı regresyon testleri (email/tckn/phone/iban/cc/dob/address)
tests/Devoplus.DataGuardian.Tests/OptionsTests.cs Options doğrulama + tip anahtarı tutarlılık testleri
tests/Devoplus.DataGuardian.Tests/MiddlewareTests.cs Middleware E2E davranış testleri (Tag/Block/Redact/filtreler)
tests/Devoplus.DataGuardian.Tests/EngineTests.cs Engine skor/filtre/overlap/weight regresyon testleri
tests/Devoplus.DataGuardian.Tests/Devoplus.DataGuardian.Tests.csproj TestHost ve güncel test paketleri
src/Devoplus.DataGuardian/SimpleLanguage.cs TR/EN dil tahminini ASCII Türkçe kelimelerle güçlendirme
src/Devoplus.DataGuardian/Recognizers/TcknRecognizer.cs TCKN’yi dil bağımsız + timeout + PiiTypes ile düzeltme
src/Devoplus.DataGuardian/Recognizers/PhoneRecognizer.cs Ulusal telefon parse’ı için region mantığı + timeout + PiiTypes
src/Devoplus.DataGuardian/Recognizers/IBANRecognizer.cs Boşluklu IBAN + mod-97 iyileştirmeleri + PiiTypes
src/Devoplus.DataGuardian/Recognizers/EmailRecognizer.cs ReDoS güvenli email regex + timeout + PiiTypes
src/Devoplus.DataGuardian/Recognizers/DobRecognizer.cs DOB kalendar/future validasyonu + timeout + PiiTypes
src/Devoplus.DataGuardian/Recognizers/CreditCardRecognizer.cs Kredi kartı regex + şema kapsamı + timeout + PiiTypes
src/Devoplus.DataGuardian/Recognizers/AddressRecognizer.cs Kelime sınırıyla adres anahtar kelime eşleştirme + timeout + PiiTypes
src/Devoplus.DataGuardian/PiiTypes.cs Tip anahtarları için tek kaynak (weights/redact/hits hizası)
src/Devoplus.DataGuardian/Internal/ResponseCaptureStream.cs Yanıtı sadece uygun içeriklerde/limit dahilinde bufferlayan stream wrapper
src/Devoplus.DataGuardian/Devoplus.DataGuardian.csproj XML doc üretimi + paket metadata + sürüm 1.1.0
src/Devoplus.DataGuardian/DataGuardianOptions.cs Yeni/iyileştirilmiş seçenekler + Validate()
src/Devoplus.DataGuardian/DataGuardianMiddleware.cs Request/response analizi, blok/redaksiyon, charset/size kontrolü, Content-Length güncelleme
src/Devoplus.DataGuardian/DataGuardianExtensions.cs DI + pipeline extension overload’ları (AddDataGuardian/UseDataGuardian)
src/Devoplus.DataGuardian/DataGuardianEngine.cs Overlap çözümü, clamp, weight(0) disable semantiği, NER filtre uygulaması
samples/Devoplus.DataGuardian.SampleApi/Program.cs Örnek API’yi DI + config binding kullanımına taşıma
samples/Devoplus.DataGuardian.SampleApi/appsettings.json Sample için DataGuardian konfig bölümü
README.md Kullanım/dokümantasyon/konfig örneklerini güncelleme
edge/dataguardian-snippet.js Edge policy’de fail-open/closed + güvenli sayı parse’ı
docs/security.md Tehdit modeli, header oracle, redaksiyon ve DoS notları
docs/scoring.md Skor formülü ve parametrelerin açıklaması
docs/recognizers.md Tanıyıcı davranışları + NER sınırlamaları
docs/edge.md Edge dağıtımı ve konfig değişkenleri
docs/contributing.md Repo yapısı + tanıyıcı ekleme/test/CI rehberi
docs/configuration.md Tüm seçeneklerin referansı
docs/actions.md Tag/Redact/Block davranışı + redaksiyon stilleri
CHANGELOG.md 1.1.0 değişiklik özeti ve migrasyon notları
.github/workflows/dotnet.yml CI: test results + coverage artifact upload
.github/dependabot.yml NuGet + GitHub Actions güncellemelerini haftalığa genişletme

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +55 to +59
public static IApplicationBuilder UseDataGuardian(this IApplicationBuilder app, Action<DataGuardianOptions> configure)
{
if (configure is null) throw new ArgumentNullException(nameof(configure));
var options = new DataGuardianOptions();
configure(options);
Comment on lines +16 to +19
static readonly Regex Rx = new(
@"\b\d(?:[ \-]?\d){12,18}\b",
RegexOptions.Compiled,
TimeSpan.FromMilliseconds(200));
Comment on lines +179 to +188
/// <summary>Reads the request body up to the size cap. Returns (body, oversize); body is null when skipped.</summary>
private async Task<(string? body, bool oversize)> ReadRequestBodyAsync(HttpContext ctx)
{
ctx.Request.EnableBuffering();
using var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8, leaveOpen: true);
var body = await reader.ReadToEndAsync();
ctx.Request.Body.Position = 0;
return body;
var stream = ctx.Request.Body;

if (ctx.Request.ContentLength is long declared && declared > _opt.MaxBodySizeBytes)
{
stream.Position = 0;
return (null, true);
Copilot AI review requested due to automatic review settings July 17, 2026 06:03
@saracmert
saracmert removed the request for review from Copilot July 17, 2026 06:03

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T13:21:03.830796Z cc5d215 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cc5d215a82

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +94 to 98
if (capture.DidPassthrough)
{
ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
await ctx.Response.WriteAsync("Blocked by DataGuardian policy.");
if (_opt.EmitHeaders && capture.Overflowed && !ctx.Response.HasStarted)
ctx.Response.Headers[$"{_opt.HeaderPrefix}-Response-Skip-Reason"] = "BodyTooLarge";
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor fail-closed for oversized responses

When an analyzable response exceeds MaxBodySizeBytes, ResponseCaptureStream spills the buffered content to the client and this branch returns without checking BlockOversizeBodies. Consequently, with Action = Block and BlockOversizeBodies = true, oversized requests are blocked but oversized responses are still delivered uninspected, defeating the documented fail-closed policy for response bodies.

Useful? React with 👍 / 👎.

Comment on lines +47 to +48
var patternHits = _recognizers.SelectMany(r => r.Analyze(text, lang)).ToList();
hits.AddRange(ResolveOverlaps(patternHits));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply entity filters before resolving overlaps

Resolving overlaps before applying IncludeEntityTypes or ExcludeEntityTypes can discard an allowed hit in favor of a hit that the subsequent filter removes. For example, with IncludeEntityTypes = { EMAIL }, 05321234567@example.com produces overlapping EMAIL and valid TR PHONE hits; the higher default PHONE weight replaces EMAIL, then the include filter removes PHONE, leaving the email completely undetected and unredacted.

Useful? React with 👍 / 👎.

Comment on lines +26 to +28
var options = new DataGuardianOptions();
section.Bind(options);
options.Validate();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Replace default sets when binding configured collections

ConfigurationBinder.Bind populates the already initialized mutable sets instead of replacing them, so configuration cannot narrow default-backed options. For example, configuring RedactTypes as only EMAIL leaves PHONE, TCKN, CREDIT_CARD, IBAN, and DOB in the set, and configuring a restricted AnalyzableContentTypes similarly retains every default; this can unexpectedly redact or buffer content that the operator explicitly omitted.

Useful? React with 👍 / 👎.

Comment on lines +63 to +64
// JCB: 16 digits, 3528-3589
if (len == 16 && p4 >= 3528 && p4 <= 3589) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept all valid JCB card lengths

The JCB branch accepts only 16-digit numbers even though JCB PANs with the same 3528–3589 prefix can be 16–19 digits, as documented by CyberSource's card-type identification reference. The regex already captures up to 19 digits, but valid Luhn-checked 17-, 18-, and 19-digit JCB values fall through every scheme branch and are therefore never detected or redacted.

Useful? React with 👍 / 👎.

Comment on lines +104 to +105
/// <summary>Default region (ISO 3166-1 alpha-2) used to parse national-format phone numbers.</summary>
public string DefaultPhoneRegion { get; set; } = "TR";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the configured phone region

DefaultPhoneRegion accepts any nonempty string, but for English or otherwise non-Turkish text that value is passed to libphonenumber for every national-format candidate. An unsupported value such as UK makes parsing throw NumberParseException, which the recognizer silently catches, so all national phone numbers are missed even though the new startup validation reports the configuration as valid.

Useful? React with 👍 / 👎.

Comment on lines +27 to +30
{
year = int.Parse(m.Groups[1].Value);
month = int.Parse(m.Groups[2].Value);
day = int.Parse(m.Groups[3].Value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict parsed DOB digits to ASCII

The date regex uses \d, which in .NET matches every Unicode decimal-digit character, but the captured groups are passed directly to int.Parse, which accepts only the basic Latin digits 0–9. Thus an otherwise date-shaped value such as ٢٠٢٤-٠١-٠١ throws FormatException during request or response analysis and can turn user-controlled content into a 500 response instead of simply being ignored. The mismatch is documented in Microsoft's references for .NET regex character classes and Unicode numeric parsing.

Useful? React with 👍 / 👎.

Comment on lines +79 to +81
[Obsolete("Use DataGuardianApplicationBuilderExtensions.UseDataGuardian instead.")]
public static IApplicationBuilder UseDataGuardian(IApplicationBuilder app, DataGuardianOptions options)
=> DataGuardianApplicationBuilderExtensions.UseDataGuardian(app, options);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the optional-null binary compatibility path

A caller compiled against the previous UseDataGuardian(IApplicationBuilder, DataGuardianOptions? options = null) API emits a two-argument call with null even when its source used app.UseDataGuardian(). That binary binds to this retained two-argument shim, which forwards the null to the new explicit-options overload and throws ArgumentNullException during startup; the new one-argument shim helps only after recompilation. Treating null as default options in this compatibility method is necessary for already compiled consumers.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants