From 7ea88d6fecc9e7ed75f4fc8c0a6a40ecbc53ef03 Mon Sep 17 00:00:00 2001 From: Karol Przybyszewski <136011+kprzybys@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:28:39 +0000 Subject: [PATCH 1/2] =?UTF-8?q?Ostrze=C5=BCenie=20o=20prawach=20--token-fi?= =?UTF-8?q?le/--pin-file=20i=20zapis=20plik=C3=B3w=20z=20prawami=200600?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/COMMANDS.md | 12 +- docs/ROADMAP.md | 6 +- src/KsefCli/CliIo.cs | 74 ++++++++- src/KsefCli/Commands/LoginCommand.cs | 1 + src/KsefCli/Commands/LoginKey.cs | 1 + tests/KsefCli.Tests/FilePermissionsTests.cs | 141 ++++++++++++++++++ .../KsefCli.Tests/KsefTestEnvironmentTests.cs | 4 + tests/KsefCli.Tests/LoginPkcs11Tests.cs | 82 ++++++++++ tests/KsefCli.Tests/LoginTokenTests.cs | 58 ++++++- 9 files changed, 364 insertions(+), 15 deletions(-) create mode 100644 tests/KsefCli.Tests/FilePermissionsTests.cs diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 15aba3a..88bd467 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -11,8 +11,8 @@ | `ksef session [-a] [--json]` | nie | Lokalne sesje: środowisko, NIP, ważność, opis środowiska (bez tokenów). Bez `-e` i `KSEF_ENV` — ze wszystkich środowisk. Kod wyjścia 1, gdy brak sesji. | | `ksef list [--subject buyer\|seller\|third\|authorized] [--from D] [--to D] [--date-type issue\|invoicing\|storage] [--json]` | tak | Metadane faktur z KSeF. Domyślnie faktury otrzymane (`buyer`) od 1. dnia bieżącego miesiąca. TSV bez nagłówka: numer KSeF, numer faktury, data wystawienia, NIP i nazwa sprzedawcy, identyfikator i nazwa nabywcy, brutto, waluta. Daty `RRRR-MM-DD` (czas lokalny, „do” włącznie) albo ISO 8601. Zakres dłuższy niż limit KSeF (100 dni) dzielony automatycznie; wynik obcięty przez KSeF do 10 000 pozycji pobierany dalej od ostatniej daty, bez powtórek. Pusty wynik to kod 0. | | `ksef send [pliki\|-]... [--json]` | tak | Wysyła faktury FA(3) w jednej sesji interaktywnej i czeka na numery KSeF. Najpierw ta sama kontrola co `validate` oraz data wystawienia nie z przyszłości — jeśli któryś plik jej nie przejdzie, nie wysyła nic. Gdy KSeF zgłosi sesję tymczasowo niedostępną (21184), wysyła dalej w nowej sesji. Gdy odpowiedź na wysyłkę nie dotrze (sieć, limit czasu, błąd bramy 408/5xx bez kodu KSeF), szuka faktury w sesji po skrócie SHA-256 — przyjętą podaje z numerem KSeF zamiast zgłaszać jako niewysłaną. Wynik TSV: numer KSeF, plik, numer sesji (do UPO); odrzucone (np. 440 duplikat z `originalKsefNumber`) na stderr. Faktura, której stanu nie da się ustalić (odpowiedź nie dotarła i nie widać jej w sesji, brak statusu, przerwanie), ma na stderr „STATUS NIEZNANY” z numerem referencyjnym, a w `--json` pole `statusUnknown` — **przed ponowną wysyłką sprawdź ją** (`ksef list --subject seller --date-type invoicing`), bo może już być wystawiona. „nie wysłano” znaczy, że do KSeF nie poszła (np. po 21184 nie dało się otworzyć nowej sesji). Ctrl+C/SIGTERM: kończy wysyłkę, wypisuje stan każdej faktury, zamyka sesje. Kod wyjścia: 0 wszystkie przyjęte, 1 jest błąd, 130 przerwano. | -| `ksef get [numery\|-]... [-d katalog]` | tak | XML faktur po numerze KSeF — bajt w bajt to, co wysłał wystawca. Numery z argumentów albo ze stdin (pierwsza kolumna TSV, więc `ksef list \| ksef get -d faktury/` działa bez `cut`). Jeden numer bez `-d`: XML na stdout. Z `-d`: pliki `.xml` (zapis atomowy), ścieżki na stdout; już pobrane pomija bez sieci. Faktura przyjęta przed chwilą, jeszcze niedostępna (KSeF 21165), jest pobierana ponownie do 1 min. Kod wyjścia: 0 wszystkie pobrane, 1 jest błąd. | -| `ksef upo [numery\|-]... [--session S] [--collective] [-d katalog]` | tak | Urzędowe Poświadczenie Odbioru (XML z podpisem MF). Dla faktur: numer KSeF + numer sesji wysyłki — wejście w formacie `ksef send` (numer KSeF, plik, sesja), więc `ksef send *.xml \| ksef upo -d upo/` działa wprost; numery bez kolumny sesji biorą `--session`. `--collective`: zbiorcze UPO sesji. UPO faktury KSeF wydaje razem z numerem KSeF, także gdy sesja jest jeszcze otwarta (np. przez inny program); zbiorcze UPO powstaje dopiero po zamknięciu sesji — przy otwartej `--collective` od razu to zgłasza, przy zamkniętej czeka (do 3 min). Jedno UPO na stdout, kilka do `-d` (`.upo.xml`, `.upo.xml`). Kod wyjścia: 0 wszystkie pobrane, 1 jest błąd. | +| `ksef get [numery\|-]... [-d katalog]` | tak | XML faktur po numerze KSeF — bajt w bajt to, co wysłał wystawca. Numery z argumentów albo ze stdin (pierwsza kolumna TSV, więc `ksef list \| ksef get -d faktury/` działa bez `cut`). Jeden numer bez `-d`: XML na stdout. Z `-d`: pliki `.xml` (zapis atomowy, prawa 0600), ścieżki na stdout; już pobrane pomija bez sieci. Faktura przyjęta przed chwilą, jeszcze niedostępna (KSeF 21165), jest pobierana ponownie do 1 min. Kod wyjścia: 0 wszystkie pobrane, 1 jest błąd. | +| `ksef upo [numery\|-]... [--session S] [--collective] [-d katalog]` | tak | Urzędowe Poświadczenie Odbioru (XML z podpisem MF). Dla faktur: numer KSeF + numer sesji wysyłki — wejście w formacie `ksef send` (numer KSeF, plik, sesja), więc `ksef send *.xml \| ksef upo -d upo/` działa wprost; numery bez kolumny sesji biorą `--session`. `--collective`: zbiorcze UPO sesji. UPO faktury KSeF wydaje razem z numerem KSeF, także gdy sesja jest jeszcze otwarta (np. przez inny program); zbiorcze UPO powstaje dopiero po zamknięciu sesji — przy otwartej `--collective` od razu to zgłasza, przy zamkniętej czeka (do 3 min). Jedno UPO na stdout, kilka do `-d` (`.upo.xml`, `.upo.xml`, zapis atomowy, prawa 0600). Kod wyjścia: 0 wszystkie pobrane, 1 jest błąd. | ## Zasady @@ -91,8 +91,9 @@ ksef login --nip 5908996669 --token-file ~/.config/ksef/token # albo z pliku ( ``` Token jest sekretem, więc `ksef` przyjmuje go tylko z pliku albo stdin, nigdy jako argument (byłby widoczny -w `ps` i historii powłoki). Liczy się pierwszy niepusty wiersz. KSeF dostaje token zaszyfrowany kluczem -publicznym MF razem z czasem wyzwania. +w `ps` i historii powłoki). Liczy się pierwszy niepusty wiersz. Gdy plik z `--token-file` jest dostępny dla +grupy lub innych, `ksef` wypisuje ostrzeżenie na stderr (z podpowiedzią `chmod 600`) i loguje się dalej. +KSeF dostaje token zaszyfrowany kluczem publicznym MF razem z czasem wyzwania. Trzecia — podpis innym programem (Profil Zaufany, aplikacja do podpisu kwalifikowanego na karcie): `ksef` wypisuje niepodpisane żądanie z wyzwaniem KSeF, a po podpisaniu je wysyła. @@ -116,7 +117,8 @@ ksef login --nip 5908996669 --cert cert.pem --key 'pkcs11:token=Karta;object=Pod ``` - PIN tylko z pliku albo stdin (`--pin-file`, pierwszy niepusty wiersz, spacje się liczą), nigdy jako argument - ani w `--key` (`pin-value=` jest odrzucane). Komunikaty modułów PKCS#11 przechwytujemy przy każdej operacji + ani w `--key` (`pin-value=` jest odrzucane). Gdy plik z `--pin-file` jest dostępny dla grupy lub innych, + `ksef` wypisuje ostrzeżenie na stderr (z podpowiedzią `chmod 600`) i działa dalej. Komunikaty modułów PKCS#11 przechwytujemy przy każdej operacji na kluczu, więc udane logowanie jest ciche, a przy błędzie PIN jest zamaskowany. Zły PIN wychodzi przed połączeniem z KSeF (próbny podpis). - `--key-via engine` (libp11, pakiet `libengine-pkcs11-openssl`) albo `provider` (`pkcs11-provider`). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index bfeb26e..5e96826 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -16,7 +16,6 @@ potoki, sekrety nigdy w argumentach. - [ ] `logout`: usunąć sesję lokalnie także wtedy, gdy KSeF odrzuci unieważnienie (token już unieważniony). - [ ] `list`: daty bez godziny w czasie polskim (jak w `send`), nie w strefie maszyny — cron na serwerze w UTC. - [ ] `get` i `upo`: błąd sieci przy jednej pozycji nie przerywa całej partii (dziś tylko błędy KSeF są per pozycja). -- [ ] Ostrzeżenie, gdy `--token-file`/`--pin-file` jest czytelny dla innych; pliki faktur i UPO z prawami 0600. - [ ] `ksef export --state PLIK` — eksport asynchroniczny (paczki ZIP) z przyrostowym pobieraniem od HWM i jawnym plikiem stanu; wynik do potoku (`| ksef get`). MF zaleca eksport zamiast serii pojedynczych pobrań (limit 64/h). @@ -47,6 +46,11 @@ potoki, sekrety nigdy w argumentach. - [ ] Uprawnienia (np. nadanie biuru rachunkowemu), limity API, dane testowe (tylko TEST). - [ ] `cert verify` — kontrola certyfikatu i klucza (próbny podpis, w tym KOD II). +## Zrobione w 0.1.5 + +- [x] Ostrzeżenie na stderr (`chmod 600`), gdy `--token-file` lub `--pin-file` jest dostępny dla grupy lub innych; + pliki faktur, UPO i inne pliki zapisywane przez `CliIo` tworzone atomowo z prawami 0600. + ## Zrobione w 0.1.4 - [x] macOS: binarki `osx-arm64` (Apple Silicon) i `osx-x64` (Intel), bez pakietów (ICU, kryptografia i libxslt diff --git a/src/KsefCli/CliIo.cs b/src/KsefCli/CliIo.cs index ead2152..8f8b37d 100644 --- a/src/KsefCli/CliIo.cs +++ b/src/KsefCli/CliIo.cs @@ -19,6 +19,11 @@ public static class CliIo { public const string StdStream = "-"; + private const UnixFileMode PrivateFileMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private const UnixFileMode GroupOrOtherPermissions = + UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; + private static readonly JsonSerializerOptions JsonOptions = KsefJson.Configure(new(JsonSerializerDefaults.Web) { WriteIndented = true, @@ -47,12 +52,12 @@ public static byte[] ReadAllBytes(string path) return buffer.ToArray(); } - /// Zapisuje gotowy wynik naraz, żeby błąd w trakcie nie zostawił połowy pliku. + /// Zapisuje gotowy wynik naraz, żeby błąd w trakcie nie zostawił połowy pliku; na Uniksie z prawami 0600. public static void WriteAllBytes(string path, byte[] content) { if (path != StdStream) { - File.WriteAllBytes(path, content); + WriteFileAtomically(path, content); return; } using Stream stdout = Console.OpenStandardOutput(); @@ -81,12 +86,41 @@ public static IReadOnlyList ReadIdentifiers(string[] args) return identifiers; } - /// Zapis przez plik tymczasowy i zmianę nazwy — przerwany zapis nie zostawia uciętego pliku. + /// + /// Zapis przez plik tymczasowy (na Uniksie tworzony od razu z prawami 0600) i zmianę nazwy — przerwany zapis + /// nie zostawia uciętego pliku, a nadpisanie istniejącego też daje prawa 0600. + /// public static void WriteFileAtomically(string path, byte[] content) { - string temp = path + ".tmp"; - File.WriteAllBytes(temp, content); - File.Move(temp, path, overwrite: true); + string temp = $"{path}.{Guid.NewGuid():N}.tmp"; + FileStreamOptions options = new() + { + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + }; + if (!OperatingSystem.IsWindows()) + { + options.UnixCreateMode = PrivateFileMode; + } + try + { + using (FileStream file = new(temp, options)) + { + file.Write(content); + } + File.Move(temp, path, overwrite: true); + } + catch + { + try + { + File.Delete(temp); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + throw; + } } /// Typ wyniku musi być w . @@ -94,4 +128,32 @@ public static void WriteJson(T value) => Console.Out.WriteLine(JsonSerializer.Serialize(value, (JsonTypeInfo)JsonOptions.GetTypeInfo(typeof(T)))); public static void Error(string message) => Console.Error.WriteLine($"ksef: {message}"); + + public static void Warning(string message) => Console.Error.WriteLine($"ksef: ostrzeżenie: {message}"); + + /// + /// Ostrzega na stderr, gdy plik z sekretem (token, PIN) ma jakiekolwiek prawa dla grupy lub innych. + /// Nie przerywa działania; pomija `-` (stdin) oraz Windows. + /// + public static void WarnIfAccessibleByOthers(string path) + { + if (path == StdStream || OperatingSystem.IsWindows()) + { + return; + } + UnixFileMode mode; + try + { + mode = File.GetUnixFileMode(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return; + } + if ((mode & GroupOrOtherPermissions) != UnixFileMode.None) + { + string octal = Convert.ToString((int)mode & 0x1FF, 8).PadLeft(4, '0'); + Warning($"{path} ma prawa {octal} (dostępny dla grupy lub innych) — ogranicz dostęp: chmod 600 {path}"); + } + } } diff --git a/src/KsefCli/Commands/LoginCommand.cs b/src/KsefCli/Commands/LoginCommand.cs index c277e93..363e5b8 100644 --- a/src/KsefCli/Commands/LoginCommand.cs +++ b/src/KsefCli/Commands/LoginCommand.cs @@ -162,6 +162,7 @@ private static async Task RunWithTokenAsync(KsefEnvironment env, string nip CliIo.Error($"{CliIo.DisplayName(tokenPath)}: brak tokenu KSeF."); return 1; } + CliIo.WarnIfAccessibleByOthers(tokenPath); try { diff --git a/src/KsefCli/Commands/LoginKey.cs b/src/KsefCli/Commands/LoginKey.cs index 5a5e196..482d8a3 100644 --- a/src/KsefCli/Commands/LoginKey.cs +++ b/src/KsefCli/Commands/LoginKey.cs @@ -67,6 +67,7 @@ private static bool TryAttachHardwareKey(X509Certificate2 certificate, HardwareK CliIo.Error($"{CliIo.DisplayName(pinFile)}: brak PIN-u."); return false; } + CliIo.WarnIfAccessibleByOthers(pinFile); } bool viaProvider = key.Via is { } via diff --git a/tests/KsefCli.Tests/FilePermissionsTests.cs b/tests/KsefCli.Tests/FilePermissionsTests.cs new file mode 100644 index 0000000..adc87f5 --- /dev/null +++ b/tests/KsefCli.Tests/FilePermissionsTests.cs @@ -0,0 +1,141 @@ +using System.Text; + +namespace KsefCli.Tests; + +/// +/// Prawa plików (0600) przy zapisie przez oraz przez komendy `get`, `upo` i `show`. +/// +public class FilePermissionsTests : IDisposable +{ + private const string Nip = "5908996669"; + private const string KsefNumber = "5908996669-20261030-7C4E9AC00000-D0"; + private const string Session = "20261030-SO-394363C000-F9191A9DA9-98"; + private const UnixFileMode Mode0600 = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private const UnixFileMode Mode0644 = Mode0600 | UnixFileMode.GroupRead | UnixFileMode.OtherRead; + private const UnixFileMode Mode0755 = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; + + private readonly TempDir dir = new(); + + public void Dispose() => dir.Dispose(); + + [Fact] + public void WriteFileAtomically_NewFile_HasMode0600() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + string path = dir.File("faktura.xml"); + byte[] content = ""u8.ToArray(); + + CliIo.WriteFileAtomically(path, content); + + Assert.Equal(Mode0600, File.GetUnixFileMode(path)); + Assert.Equal(content, File.ReadAllBytes(path)); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } + + [Fact] + public void WriteFileAtomically_OverwritesExisting0644File_WithMode0600() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + string path = dir.File("istniejaca.xml"); + File.WriteAllBytes(path, "stare"u8.ToArray()); + File.SetUnixFileMode(path, Mode0644); + byte[] updated = "nowe"u8.ToArray(); + + CliIo.WriteFileAtomically(path, updated); + + Assert.Equal(Mode0600, File.GetUnixFileMode(path)); + Assert.Equal(updated, File.ReadAllBytes(path)); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } + + [Fact] + public void WriteAllBytes_NewFile_HasMode0600() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + string path = dir.File("wynik.html"); + byte[] content = ""u8.ToArray(); + + CliIo.WriteAllBytes(path, content); + + Assert.Equal(Mode0600, File.GetUnixFileMode(path)); + Assert.Equal(content, File.ReadAllBytes(path)); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } + + [Fact] + public void WriteAllBytes_OverwritesExisting0644File_WithMode0600() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + string path = dir.File("istniejacy.html"); + File.WriteAllBytes(path, "stare"u8.ToArray()); + File.SetUnixFileMode(path, Mode0644); + byte[] updated = "nowe"u8.ToArray(); + + CliIo.WriteAllBytes(path, updated); + + Assert.Equal(Mode0600, File.GetUnixFileMode(path)); + Assert.Equal(updated, File.ReadAllBytes(path)); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } + + [Fact] + public async Task Get_ToDirectory_CreatesMode0600Files_WithoutChangingDirectoryPermissions() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + using FakeKsef ksef = new(); + ksef.On("GET", $"invoices/ksef/{KsefNumber}", (_, _) => FakeResponse.Xml($"{KsefNumber}")); + FakeKsef.WriteLoginSession(dir.Path, Nip); + string outDir = dir.File("faktury"); + Directory.CreateDirectory(outDir); + File.SetUnixFileMode(outDir, Mode0755); + + CliResult result = await ksef.RunAsync(dir.Path, "get", "-d", outDir, KsefNumber); + + Assert.True(result.ExitCode == 0, result.Stderr); + string saved = Path.Combine(outDir, $"{KsefNumber}.xml"); + Assert.Equal(Mode0600, File.GetUnixFileMode(saved)); + Assert.Equal(Mode0755, File.GetUnixFileMode(outDir)); + Assert.Empty(Directory.GetFiles(outDir, "*.tmp")); + } + + [Fact] + public async Task Upo_ToDirectory_CreatesMode0600Files_WithoutChangingDirectoryPermissions() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + using FakeKsef ksef = new(); + ksef.On("GET", $"sessions/{Session}/invoices/ksef/{KsefNumber}/upo", + (_, _) => FakeResponse.Xml($"{KsefNumber}")); + FakeKsef.WriteLoginSession(dir.Path, Nip); + string outDir = dir.File("upo"); + Directory.CreateDirectory(outDir); + File.SetUnixFileMode(outDir, Mode0755); + + CliResult result = await ksef.RunAsync(dir.Path, "upo", "--session", Session, "-d", outDir, KsefNumber); + + Assert.True(result.ExitCode == 0, result.Stderr); + string saved = Path.Combine(outDir, $"{KsefNumber}.upo.xml"); + Assert.Equal(Mode0600, File.GetUnixFileMode(saved)); + Assert.Equal(Mode0755, File.GetUnixFileMode(outDir)); + Assert.Empty(Directory.GetFiles(outDir, "*.tmp")); + } + + [Fact] + public async Task Show_ToOutputFile_Creates0600_AndOverwrites0644With0600() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + byte[] invoice = TestData.ValidInvoice(); + string output = dir.File("podglad.html"); + + CliResult created = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr", "-o", output); + Assert.True(created.ExitCode == 0, created.Stderr); + Assert.Equal(Mode0600, File.GetUnixFileMode(output)); + + File.SetUnixFileMode(output, Mode0644); + CliResult overwritten = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr", "-o", output); + Assert.True(overwritten.ExitCode == 0, overwritten.Stderr); + Assert.Equal(Mode0600, File.GetUnixFileMode(output)); + Assert.NotEmpty(Encoding.UTF8.GetString(File.ReadAllBytes(output))); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } +} diff --git a/tests/KsefCli.Tests/KsefTestEnvironmentTests.cs b/tests/KsefCli.Tests/KsefTestEnvironmentTests.cs index 61a12b6..fdcdca1 100644 --- a/tests/KsefCli.Tests/KsefTestEnvironmentTests.cs +++ b/tests/KsefCli.Tests/KsefTestEnvironmentTests.cs @@ -143,6 +143,10 @@ public async Task Login_KsefToken_WorksUntilRevoked() string tokenFile = Path.Combine(runtime.Path, "ksef-token"); File.WriteAllText(tokenFile, token.Token + "\n"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(tokenFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } CliResult login = await Ksef("login", "--nip", nip, "--token-file", tokenFile); Assert.True(login.ExitCode == 0, login.Stderr); Assert.Empty(login.StdoutBytes); diff --git a/tests/KsefCli.Tests/LoginPkcs11Tests.cs b/tests/KsefCli.Tests/LoginPkcs11Tests.cs index 62f8f32..6b1ef02 100644 --- a/tests/KsefCli.Tests/LoginPkcs11Tests.cs +++ b/tests/KsefCli.Tests/LoginPkcs11Tests.cs @@ -28,6 +28,10 @@ private SoftHsmToken(string nip, string pin) CertificateFile = dir.File("cert.pem"); PinFile = dir.File("pin"); File.WriteAllText(PinFile, pin + "\n"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(PinFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } } public string TokenPin { get; } @@ -167,6 +171,10 @@ public async Task Login_WrongPin_ExplainsWithoutRevealingPin() using TempDir dir = new(); string pinFile = dir.File("pin"); await File.WriteAllTextAsync(pinFile, "480613", TestContext.Current.CancellationToken); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(pinFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } CliResult login = await ksef.RunAsync(dir.Path, null, token.Environment, "login", "--nip", Nip, "--cert", token.CertificateFile, "--key", token.Uri, "--pin-file", pinFile, "--key-via", "engine"); @@ -177,6 +185,24 @@ public async Task Login_WrongPin_ExplainsWithoutRevealingPin() Assert.Empty(ksef.RequestsTo("POST", "auth/challenge")); } + [Fact] + public async Task Login_PinFileAccessibleByOthers_WarnsAndStillSucceeds() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + using SoftHsmToken token = await SoftHsmToken.CreateAsync(Nip); + using FakeKsef ksef = LoginExternalTests.AuthenticatingKsef(); + using TempDir dir = new(); + File.SetUnixFileMode(token.PinFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + + CliResult login = await ksef.RunAsync(dir.Path, null, token.Environment, + "login", "--nip", Nip, "--cert", token.CertificateFile, "--key", token.Uri, "--pin-file", token.PinFile, "--key-via", "engine"); + + Assert.Equal(0, login.ExitCode); + Assert.StartsWith("ksef: ostrzeżenie: ", login.Stderr, StringComparison.Ordinal); + Assert.Contains($"chmod 600 {token.PinFile}", login.Stderr, StringComparison.Ordinal); + Assert.DoesNotContain(SoftHsmToken.Pin, login.Stderr, StringComparison.Ordinal); + } + [Fact] public async Task Login_PinWithSpaces_IsKeptAsIs() { @@ -200,6 +226,10 @@ public async Task Login_Provider_WrongPin_FailsBeforeNetworkWithoutRevealingPin( using TempDir dir = new(); string pinFile = dir.File("pin"); await File.WriteAllTextAsync(pinFile, "480613", TestContext.Current.CancellationToken); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(pinFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } CliResult login = await ksef.RunAsync(dir.Path, null, token.Environment, "login", "--nip", Nip, "--cert", token.CertificateFile, "--key", token.Uri, "--pin-file", pinFile, "--key-via", "provider"); @@ -258,6 +288,10 @@ public async Task Login_MissingOpenSslModule_NamesPackageAndAlternative(string v string cert = dir.File("cert.pem"); string pin = dir.File("pin"); await File.WriteAllTextAsync(pin, "1234", TestContext.Current.CancellationToken); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(pin, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } Assert.Equal(0, (await Ksef.RunAsync(dir.Path, "cert", "new", "--nip", "5908996669", "-o", cert)).ExitCode); string empty = dir.File("brak-modulow"); Directory.CreateDirectory(empty); @@ -278,4 +312,52 @@ public async Task Login_MissingOpenSslModule_NamesPackageAndAlternative(string v Assert.Contains(accepted, a => result.Stderr.Contains(a, StringComparison.Ordinal)); Assert.Contains(alternative, result.Stderr, StringComparison.Ordinal); } + + [Fact] + public async Task Login_PinFileAccessibleByOthers_WarnsWithoutRevealingPin() + { + Assert.SkipWhen(OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(), "PKCS#11 tylko na Linuksie"); + using TempDir dir = new(); + string cert = dir.File("cert.pem"); + string pin = dir.File("pin"); + await File.WriteAllTextAsync(pin, "918273\n", TestContext.Current.CancellationToken); + File.SetUnixFileMode(pin, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + Assert.Equal(0, (await Ksef.RunAsync(dir.Path, "cert", "new", "--nip", "5908996669", "-o", cert)).ExitCode); + string empty = dir.File("brak-modulow"); + Directory.CreateDirectory(empty); + Dictionary environment = new(StringComparer.Ordinal) { ["OPENSSL_ENGINES"] = empty, ["OPENSSL_MODULES"] = empty }; + + CliResult result = await Ksef.RunAsync(dir.Path, null, environment, + "login", "--nip", "5908996669", "--cert", cert, "--key", SoftHsmToken.KeyUri, "--pin-file", pin, "--key-via", "provider"); + + Assert.StartsWith("ksef: ostrzeżenie: ", result.Stderr, StringComparison.Ordinal); + Assert.Contains($"chmod 600 {pin}", result.Stderr, StringComparison.Ordinal); + Assert.DoesNotContain("918273", result.Stderr, StringComparison.Ordinal); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Login_PinFilePrivateOrStdin_NoPermissionWarning(bool fromStdin) + { + Assert.SkipWhen(OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(), "PKCS#11 tylko na Linuksie"); + using TempDir dir = new(); + string cert = dir.File("cert.pem"); + string pin = dir.File("pin"); + await File.WriteAllTextAsync(pin, "918273\n", TestContext.Current.CancellationToken); + File.SetUnixFileMode(pin, UnixFileMode.UserRead | UnixFileMode.UserWrite); + Assert.Equal(0, (await Ksef.RunAsync(dir.Path, "cert", "new", "--nip", "5908996669", "-o", cert)).ExitCode); + string empty = dir.File("brak-modulow"); + Directory.CreateDirectory(empty); + Dictionary environment = new(StringComparer.Ordinal) { ["OPENSSL_ENGINES"] = empty, ["OPENSSL_MODULES"] = empty }; + + CliResult result = fromStdin + ? await Ksef.RunAsync(dir.Path, System.Text.Encoding.UTF8.GetBytes("918273\n"), environment, + "login", "--nip", "5908996669", "--cert", cert, "--key", SoftHsmToken.KeyUri, "--pin-file", "-", "--key-via", "provider") + : await Ksef.RunAsync(dir.Path, null, environment, + "login", "--nip", "5908996669", "--cert", cert, "--key", SoftHsmToken.KeyUri, "--pin-file", pin, "--key-via", "provider"); + + Assert.DoesNotContain("ostrzeżenie", result.Stderr, StringComparison.Ordinal); + Assert.DoesNotContain("chmod 600", result.Stderr, StringComparison.Ordinal); + } } diff --git a/tests/KsefCli.Tests/LoginTokenTests.cs b/tests/KsefCli.Tests/LoginTokenTests.cs index fb08fe7..6edcde2 100644 --- a/tests/KsefCli.Tests/LoginTokenTests.cs +++ b/tests/KsefCli.Tests/LoginTokenTests.cs @@ -42,6 +42,15 @@ private static FakeKsef AuthenticatingKsef(int status = 200, string description return ksef; } + private static void WritePrivateFile(string path, string content) + { + File.WriteAllText(path, content); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + [Theory] [InlineData(false)] [InlineData(true)] @@ -51,13 +60,14 @@ public async Task Login_Token_SendsEncryptedTokenWithChallengeTime_SavesSession( using TempDir dir = new(); // Plik z pustym wierszem na początku i końcem wiersza — tak go zostawia edytor albo `echo`. string file = dir.File("token"); - File.WriteAllText(file, $"\n{Token}\n"); + WritePrivateFile(file, $"\n{Token}\n"); CliResult login = fromStdin ? await ksef.RunAsync(dir.Path, Encoding.UTF8.GetBytes($"{Token}\n"), "login", "--nip", Nip, "--token-file", "-") : await ksef.RunAsync(dir.Path, "login", "--nip", Nip, "--token-file", file); Assert.True(login.ExitCode == 0, login.Stderr); + Assert.Equal("", login.Stderr); Assert.Empty(login.StdoutBytes); FakeRequest submission = Assert.Single(ksef.RequestsTo("POST", "auth/ksef-token")); @@ -76,13 +86,55 @@ public async Task Login_Token_SendsEncryptedTokenWithChallengeTime_SavesSession( Assert.Equal(Reference, (string?)saved["referenceNumber"]); } + [Theory] + [InlineData(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead)] + [InlineData(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead)] + [InlineData(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.OtherRead)] + [InlineData(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.OtherExecute)] + public async Task Login_TokenFileAccessibleByOthers_WarnsAndStillSucceeds(UnixFileMode mode) + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + using FakeKsef ksef = AuthenticatingKsef(); + using TempDir dir = new(); + string file = dir.File("token"); + File.WriteAllText(file, $"{Token}\n"); + File.SetUnixFileMode(file, mode); + + CliResult login = await ksef.RunAsync(dir.Path, "login", "--nip", Nip, "--token-file", file); + + Assert.Equal(0, login.ExitCode); + Assert.Empty(login.StdoutBytes); + Assert.StartsWith("ksef: ostrzeżenie: ", login.Stderr, StringComparison.Ordinal); + Assert.Contains($"chmod 600 {file}", login.Stderr, StringComparison.Ordinal); + Assert.DoesNotContain("0123456789abcdef", login.Stderr, StringComparison.Ordinal); + Assert.Equal(0, (await ksef.RunAsync(dir.Path, "session")).ExitCode); + } + + [Theory] + [InlineData(UnixFileMode.UserRead | UnixFileMode.UserWrite)] + [InlineData(UnixFileMode.UserRead)] + public async Task Login_TokenFilePrivate_NoWarning(UnixFileMode mode) + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "prawa plików tylko na systemach uniksowych"); + using FakeKsef ksef = AuthenticatingKsef(); + using TempDir dir = new(); + string file = dir.File("token"); + File.WriteAllText(file, $"{Token}\n"); + File.SetUnixFileMode(file, mode); + + CliResult login = await ksef.RunAsync(dir.Path, "login", "--nip", Nip, "--token-file", file); + + Assert.True(login.ExitCode == 0, login.Stderr); + Assert.Equal("", login.Stderr); + } + [Fact] public async Task Login_Token_Rejected_ShowsKsefReasonAndSavesNothing() { using FakeKsef ksef = AuthenticatingKsef(450, "Uwierzytelnianie zakończone niepowodzeniem z powodu błędnego tokenu"); using TempDir dir = new(); string file = dir.File("token"); - File.WriteAllText(file, Token); + WritePrivateFile(file, Token); CliResult login = await ksef.RunAsync(dir.Path, "login", "--nip", Nip, "--token-file", file); @@ -102,7 +154,7 @@ public async Task Login_Token_RejectedOnProduction_HasNoEnvironmentHint() using FakeKsef ksef = AuthenticatingKsef(450, "Uwierzytelnianie zakończone niepowodzeniem z powodu błędnego tokenu"); using TempDir dir = new(); string file = dir.File("token"); - File.WriteAllText(file, Token); + WritePrivateFile(file, Token); CliResult login = await ksef.RunAsync(dir.Path, "-e", "prod", "login", "--nip", Nip, "--token-file", file); From 823f7df66d1b0c9afe65764090264de1b9b00c9f Mon Sep 17 00:00:00 2001 From: Karol Przybyszewski <136011+kprzybys@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:06:42 +0000 Subject: [PATCH 2/2] =?UTF-8?q?CliIo.WriteAllBytes:=20zapis=20bezpo=C5=9Br?= =?UTF-8?q?edni=20do=20/dev/*,=20/proc/*=20i=20FIFO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/KsefCli/CliIo.cs | 39 ++++++- tests/KsefCli.Tests/FilePermissionsTests.cs | 110 +++++++++++++++++++- 2 files changed, 143 insertions(+), 6 deletions(-) diff --git a/src/KsefCli/CliIo.cs b/src/KsefCli/CliIo.cs index 8f8b37d..7927c06 100644 --- a/src/KsefCli/CliIo.cs +++ b/src/KsefCli/CliIo.cs @@ -52,18 +52,47 @@ public static byte[] ReadAllBytes(string path) return buffer.ToArray(); } - /// Zapisuje gotowy wynik naraz, żeby błąd w trakcie nie zostawił połowy pliku; na Uniksie z prawami 0600. + /// + /// Zapisuje gotowy wynik naraz, żeby błąd w trakcie nie zostawił połowy pliku. + /// Dla ścieżki innej niż `-` na systemach uniksowych: + /// (a) gdy ścieżka podana przez użytkownika (przed rozwiązaniem dowiązań) zaczyna się od `/dev/` lub `/proc/`, + /// zapisuje bezpośrednio do celu bez pliku tymczasowego i bez zmiany praw (np. `/dev/null`, `/dev/stdout`); + /// (b) gdy cel już istnieje i otwarty bez obcinania ma == false (FIFO, potok, + /// gniazdo, terminal), zapisuje bezpośrednio do tego strumienia; + /// (c) w pozostałych przypadkach zapisuje atomowo przez plik tymczasowy z prawami 0600. + /// public static void WriteAllBytes(string path, byte[] content) { - if (path != StdStream) + if (path == StdStream) { - WriteFileAtomically(path, content); + using Stream stdout = Console.OpenStandardOutput(); + stdout.Write(content); return; } - using Stream stdout = Console.OpenStandardOutput(); - stdout.Write(content); + if (!OperatingSystem.IsWindows()) + { + if (IsSpecialPath(path)) + { + using FileStream direct = new(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); + direct.Write(content); + return; + } + if (File.Exists(path)) + { + using FileStream existing = new(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); + if (!existing.CanSeek) + { + existing.Write(content); + return; + } + } + } + WriteFileAtomically(path, content); } + private static bool IsSpecialPath(string path) => + path.StartsWith("/dev/", StringComparison.Ordinal) || path.StartsWith("/proc/", StringComparison.Ordinal); + /// /// Identyfikatory z argumentów albo — gdy brak lub `-` — ze stdin, po jednym w wierszu; z wiersza bierzemy /// pierwszą kolumnę TSV, więc wynik `ksef list` / `ksef send` można przekazać dalej bez `cut`. diff --git a/tests/KsefCli.Tests/FilePermissionsTests.cs b/tests/KsefCli.Tests/FilePermissionsTests.cs index adc87f5..26a05bb 100644 --- a/tests/KsefCli.Tests/FilePermissionsTests.cs +++ b/tests/KsefCli.Tests/FilePermissionsTests.cs @@ -1,9 +1,11 @@ +using System.Diagnostics; using System.Text; namespace KsefCli.Tests; /// -/// Prawa plików (0600) przy zapisie przez oraz przez komendy `get`, `upo` i `show`. +/// Prawa plików (0600) przy zapisie przez oraz przez komendy `get`, `upo` i `show`, +/// a także zapis bezpośredni do plików specjalnych (`/dev/null`, `/dev/stdout`, FIFO). /// public class FilePermissionsTests : IDisposable { @@ -79,6 +81,25 @@ public void WriteAllBytes_OverwritesExisting0644File_WithMode0600() Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); } + [Fact] + public async Task WriteAllBytes_ToFifo_DeliversContentWithoutReplacingFifo() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "FIFO tylko na systemach uniksowych"); + string fifo = dir.File("wyjscie.fifo"); + CreateFifo(fifo); + byte[] content = "z-potoku"u8.ToArray(); + + Task reader = Task.Run(() => File.ReadAllBytes(fifo), TestContext.Current.CancellationToken); + CliIo.WriteAllBytes(fifo, content); + byte[] received = await reader.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken); + + Assert.Equal(content, received); + // FIFO nie został zastąpiony zwykłym plikiem. + using FileStream probe = new(fifo, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); + Assert.False(probe.CanSeek); + Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); + } + [Fact] public async Task Get_ToDirectory_CreatesMode0600Files_WithoutChangingDirectoryPermissions() { @@ -138,4 +159,91 @@ public async Task Show_ToOutputFile_Creates0600_AndOverwrites0644With0600() Assert.NotEmpty(Encoding.UTF8.GetString(File.ReadAllBytes(output))); Assert.Empty(Directory.GetFiles(dir.Path, "*.tmp")); } + + [Fact] + public async Task Show_ToDevNull_Succeeds() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "pliki specjalne tylko na systemach uniksowych"); + + CliResult result = await Ksef.RunAsync(dir.Path, TestData.ValidInvoice(), "show", "--no-qr", "-o", "/dev/null"); + + Assert.True(result.ExitCode == 0, result.Stderr); + Assert.Equal("", result.Stderr); + Assert.Empty(result.StdoutBytes); + } + + [Fact] + public async Task Show_ToDevStdout_WithRedirectedPipe_WritesToStdout() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "pliki specjalne tylko na systemach uniksowych"); + byte[] invoice = TestData.ValidInvoice(); + CliResult expected = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr"); + Assert.True(expected.ExitCode == 0, expected.Stderr); + + CliResult result = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr", "-o", "/dev/stdout"); + + Assert.True(result.ExitCode == 0, result.Stderr); + Assert.Equal("", result.Stderr); + Assert.Equal(expected.StdoutBytes, result.StdoutBytes); + } + + [Fact] + public async Task Show_ToDevStdout_WithRedirectedFile_WritesToFile() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "pliki specjalne tylko na systemach uniksowych"); + string invoicePath = dir.File("faktura.xml"); + File.WriteAllBytes(invoicePath, TestData.ValidInvoice()); + string outputPath = dir.File("stdout.html"); + CliResult expected = await Ksef.RunAsync(dir.Path, "show", "--no-qr", invoicePath); + Assert.True(expected.ExitCode == 0, expected.Stderr); + + ProcessStartInfo start = new("/bin/sh") + { + RedirectStandardError = true, + UseShellExecute = false, + }; + start.ArgumentList.Add("-c"); + start.ArgumentList.Add($"{Ksef.CommandLine} show --no-qr \"$1\" -o /dev/stdout > \"$2\""); + start.ArgumentList.Add("_"); + start.ArgumentList.Add(invoicePath); + start.ArgumentList.Add(outputPath); + start.Environment["XDG_RUNTIME_DIR"] = dir.Path; + + using Process process = Process.Start(start)!; + string stderr = await process.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken); + await process.WaitForExitAsync(TestContext.Current.CancellationToken); + + Assert.True(process.ExitCode == 0, stderr); + Assert.Equal("", stderr); + Assert.Equal(expected.StdoutBytes, await File.ReadAllBytesAsync(outputPath, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Show_ToFifo_DeliversContent() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "FIFO tylko na systemach uniksowych"); + byte[] invoice = TestData.ValidInvoice(); + CliResult expected = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr"); + Assert.True(expected.ExitCode == 0, expected.Stderr); + string fifo = dir.File("show.fifo"); + CreateFifo(fifo); + + Task reader = Task.Run(() => File.ReadAllBytes(fifo), TestContext.Current.CancellationToken); + CliResult result = await Ksef.RunAsync(dir.Path, invoice, "show", "--no-qr", "-o", fifo); + byte[] received = await reader.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken); + + Assert.True(result.ExitCode == 0, result.Stderr); + Assert.Equal("", result.Stderr); + Assert.Equal(expected.StdoutBytes, received); + } + + private static void CreateFifo(string path) + { + ProcessStartInfo start = new("mkfifo") { RedirectStandardError = true, UseShellExecute = false }; + start.ArgumentList.Add(path); + using Process process = Process.Start(start)!; + string stderr = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.True(process.ExitCode == 0, $"mkfifo: {stderr}"); + } }