team-ljyzipelo

공개

확대 요청의 선택 목록 전송 한도를 맞춘다

작성자
시로사키 하나
작성 시각
커밋
5a24bd56039c7d87c80ec49d3d7b746e944ce1ea
부모
a4c344d
이 시점의 파일 보기

변경된 파일 5개

+333-23
수정experiments/rust-archive-worker/README.md+1-0
@@ -6,6 +6,7 @@
66- ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다.
77- ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 기존 Start와 StartInteractive의 limits는 이 값을 낮출 수 있습니다. 별도 StartGuarded의 승인 흐름은 아래 절을 따릅니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다.
88- 경로 깊이는 64개 구성 요소이며 승인 전 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 유효한 StartGuarded 자원 승인 후에만 각각 64 MiB와 262,144개로 확대합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
9추가: - 선택 ID 전송은 Start와 StartInteractive 및 항목 상한을 늘리지 않은 StartGuarded에서 기존 32,768개를 유지합니다. 항목 상한을 늘린 StartGuarded는 32,768개와 요청 ceiling.entries 중 큰 값까지 전송하며 최대 200,000개입니다. 전송만으로 승인이 성립하지 않으며 실제 처리는 일치하는 ResourceReply 허용 뒤에 시작합니다. 경로/문자열, 생성 원본 벡터와 프레임 한도는 확대하지 않습니다.
910- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
1011- ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
1112- 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다.
수정experiments/rust-archive-worker/src/wire.rs+55-23
@@ -3,11 +3,14 @@ use std::io::{self, Read, Write};
33
44pub const MAX_BODY: usize = 1_048_576;
55pub const MAX_FRAMES: u64 = 1_000_000;
6추가: const LEGACY_VECTOR_ITEMS: usize = 32_768;
7추가: const MAX_SELECTION_IDS: usize = 200_000;
68fn invalid() -> io::Error {
79 io::Error::new(io::ErrorKind::InvalidData, "invalid worker frame")
810}
911struct Encoder {
1012 bytes: Vec<u8>,
13추가: selection_limit: usize,
1114}
1215impl Encoder {
1316 fn put(&mut self, b: &[u8]) -> io::Result<()> {
@@ -27,6 +30,7 @@ impl Encoder {
2730struct Decoder<'a> {
2831 bytes: &'a [u8],
2932 at: usize,
33추가: selection_limit: usize,
3034}
3135impl<'a> Decoder<'a> {
3236 fn take(&mut self, n: usize) -> io::Result<&'a [u8]> {
@@ -81,28 +85,34 @@ impl<T: Wire> Wire for Option<T> {
8185 }
8286 }
8387}
88추가: fn encode_vec<T: Wire>(values: &[T], limit: usize, e: &mut Encoder) -> io::Result<()> {
89추가: if values.len() > limit {
90추가: return Err(invalid());
91추가: }
92추가: (values.len() as u32).enc(e)?;
93추가: for value in values {
94추가: value.enc(e)?;
95추가: }
96추가: Ok(())
97추가: }
98추가: fn decode_vec<T: Wire>(limit: usize, d: &mut Decoder<'_>) -> io::Result<Vec<T>> {
99추가: let n = u32::dec(d)? as usize;
100추가: if n > limit || n > d.bytes.len() - d.at {
101추가: return Err(invalid());
102추가: }
103추가: let mut values = Vec::new();
104추가: values.try_reserve(n).map_err(|_| invalid())?;
105추가: for _ in 0..n {
106추가: values.push(T::dec(d)?);
107추가: }
108추가: Ok(values)
109추가: }
84110impl<T: Wire> Wire for Vec<T> {
85111 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
86삭제: if self.len() > 32768 {
87삭제: return Err(invalid());
88삭제: }
89삭제: (self.len() as u32).enc(e)?;
90삭제: for v in self {
91삭제: v.enc(e)?;
92삭제: }
93삭제: Ok(())
112추가: encode_vec(self, LEGACY_VECTOR_ITEMS, e)
94113 }
95114 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
96삭제: let n = u32::dec(d)? as usize;
97삭제: if n > 32768 || n > d.bytes.len() - d.at {
98삭제: return Err(invalid());
99삭제: }
100삭제: let mut v = Vec::new();
101삭제: v.try_reserve(n).map_err(|_| invalid())?;
102삭제: for _ in 0..n {
103삭제: v.push(T::dec(d)?);
104삭제: }
105삭제: Ok(v)
115추가: decode_vec(LEGACY_VECTOR_ITEMS, d)
106116 }
107117}
108118impl Wire for String {
@@ -254,14 +264,14 @@ impl Wire for Selection {
254264 Self::All => 0u8.enc(e),
255265 Self::EntryIds(ids) => {
256266 1u8.enc(e)?;
257삭제: ids.enc(e)
267추가: encode_vec(ids, e.selection_limit, e)
258268 }
259269 }
260270 }
261271 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
262272 match u8::dec(d)? {
263273 0 => Ok(Self::All),
264삭제: 1 => Ok(Self::EntryIds(Wire::dec(d)?)),
274추가: 1 => Ok(Self::EntryIds(decode_vec(d.selection_limit, d)?)),
265275 _ => Err(invalid()),
266276 }
267277 }
@@ -325,7 +335,10 @@ impl Wire for Action {
325335}
326336impl Message {
327337 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
328삭제: let mut e = Encoder { bytes: Vec::new() };
338추가: let mut e = Encoder {
339추가: bytes: Vec::new(),
340추가: selection_limit: LEGACY_VECTOR_ITEMS,
341추가: };
329342 let kind = match self {
330343 Self::Start(v) => {
331344 v.enc(&mut e)?;
@@ -364,6 +377,7 @@ impl Message {
364377 if !v.valid() {
365378 return Err(invalid());
366379 }
380추가: e.selection_limit = LEGACY_VECTOR_ITEMS.max(v.ceiling.entries as usize);
367381 v.enc(&mut e)?;
368382 6
369383 }
@@ -485,7 +499,15 @@ impl Message {
485499 Ok((kind, e.bytes))
486500 }
487501 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
488삭제: let mut d = Decoder { bytes: b, at: 0 };
502추가: let mut d = Decoder {
503추가: bytes: b,
504추가: at: 0,
505추가: selection_limit: if kind == 6 {
506추가: MAX_SELECTION_IDS
507추가: } else {
508추가: LEGACY_VECTOR_ITEMS
509추가: },
510추가: };
489511 let m = match kind {
490512 1 => Self::Start(Wire::dec(&mut d)?),
491513 2 => {
@@ -514,7 +536,13 @@ impl Message {
514536 },
515537 6 => {
516538 let start = GuardedStart::dec(&mut d)?;
517삭제: if !start.valid() {
539추가: let limit = LEGACY_VECTOR_ITEMS.max(start.ceiling.entries as usize);
540추가: if !start.valid()
541추가: || matches!(
542추가: &start.start.action,
543추가: Action::Extract { selection: Selection::EntryIds(ids), .. } if ids.len() > limit
544추가: )
545추가: {
518546 return Err(invalid());
519547 }
520548 Self::StartGuarded(start)
@@ -677,3 +705,7 @@ impl<W: Write> Writer<W> {
677705 Ok(())
678706 }
679707}
708추가:
709추가: #[cfg(test)]
710추가: #[path = "../../../tests/rust-archive-worker/selection_wire.rs"]
711추가: mod tests;
수정tests/rust-archive-worker/guarded.rs+80-0
@@ -858,3 +858,83 @@ fn zip_creation_still_stops_after_sixty_seconds_without_progress() {
858858 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
859859 assert!(!s.0.join("new.zip").exists());
860860}
861추가:
862추가: #[cfg(target_os = "linux")]
863추가: #[test]
864추가: fn large_selection_reaches_worker_permission_and_destination_checks() {
865추가: let s = setup();
866추가: generate(&s, "selection-entries");
867추가: let mut start = request(&s, Limits::default().output, Limits::default().output);
868추가: start.start.action = Action::List {
869추가: archive: s.path("input"),
870추가: };
871추가: let mut count = 0;
872추가: let mut list_id = None;
873추가: let events = run_record(&s, start, None, false, |event| {
874추가: match event {
875추가: Message::Entry(entry) => {
876추가: assert_eq!(entry.entry_id, count);
877추가: count += 1;
878추가: }
879추가: Message::ListEnd { list_id: id, .. } => list_id = Some(id.clone()),
880추가: _ => {}
881추가: }
882추가: approve(event)
883추가: });
884추가: assert_eq!(terminal(&events).outcome, Outcome::Completed);
885추가: assert_eq!(count, 32_770);
886추가: let list_id = list_id.unwrap();
887추가: for decision in 0..3 {
888추가: let mut start = request(&s, Limits::default().output, Limits::default().output);
889추가: if let Action::Extract {
890추가: selection,
891추가: list_id: token,
892추가: ..
893추가: } = &mut start.start.action
894추가: {
895추가: *selection = Selection::EntryIds((0..32_769).collect());
896추가: *token = Some(list_id.clone());
897추가: }
898추가: let mut asked = false;
899추가: let events = run_fault(&s, start, Some("space-destination"), |event| {
900추가: if let Message::ResourceRequired {
901추가: challenge_id,
902추가: scope,
903추가: ..
904추가: } = event
905추가: {
906추가: asked = true;
907추가: assert!(scope.entries && !scope.output && !scope.ratio);
908추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
909추가: return Some(if decision == 1 {
910추가: vec![Message::Cancel]
911추가: } else {
912추가: vec![Message::ResourceReply {
913추가: challenge_id: *challenge_id,
914추가: scope: *scope,
915추가: allow: decision == 2,
916추가: }]
917추가: });
918추가: }
919추가: None
920추가: });
921추가: assert!(asked);
922추가: assert_eq!(
923추가: terminal(&events).outcome,
924추가: if decision == 2 {
925추가: Outcome::Failed
926추가: } else {
927추가: Outcome::Cancelled
928추가: },
929추가: "{decision}: {events:?}"
930추가: );
931추가: if decision == 2 {
932추가: assert_eq!(terminal(&events).error, ErrorCode::DiskFull);
933추가: assert!(s.0.join("marker").exists());
934추가: }
935추가: assert_eq!(terminal(&events).publication, Publication::None);
936추가: assert_eq!(terminal(&events).created_count, 0);
937추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
938추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
939추가: }
940추가: }
수정tests/rust-archive-worker/guarded_cases.py+4-0
@@ -21,6 +21,10 @@ elif case == "many-entries":
2121 with zipfile.ZipFile(root / "input", "w") as archive:
2222 for entry_id in range(200_000):
2323 archive.writestr(f"e{entry_id}", b"")
24추가: elif case == "selection-entries":
25추가: with zipfile.ZipFile(root / "input", "w") as archive:
26추가: for entry_id in range(32_770):
27추가: archive.writestr(f"e{entry_id}", b"x")
2428elif case == "empty-directories":
2529 with zipfile.ZipFile(root / "input", "w") as archive:
2630 for entry_id in range(36):
추가tests/rust-archive-worker/selection_wire.rs+193-0
@@ -0,0 +1,193 @@
1추가: use super::*;
2추가:
3추가: const ARCHIVE: &[u8] = b"/archive";
4추가: const DESTINATION: &[u8] = b"/destination";
5추가:
6추가: fn request(count: usize, kind: u16, ceiling: u32) -> Message {
7추가: let start = Start {
8추가: action: Action::Extract {
9추가: archive: NativePath::Unix(ARCHIVE.to_vec()),
10추가: destination: NativePath::Unix(DESTINATION.to_vec()),
11추가: selection: Selection::EntryIds((0..count as u32).collect()),
12추가: list_id: None,
13추가: gzip_output_name: None,
14추가: },
15추가: limits: Limits::default(),
16추가: };
17추가: match kind {
18추가: 1 => Message::Start(start),
19추가: 4 => Message::StartInteractive(start),
20추가: 6 => Message::StartGuarded(GuardedStart {
21추가: ceiling: Limits {
22추가: entries: ceiling,
23추가: ..start.limits
24추가: },
25추가: start,
26추가: interactive: true,
27추가: }),
28추가: _ => unreachable!(),
29추가: }
30추가: }
31추가:
32추가: fn encoded(message: &Message) -> Vec<u8> {
33추가: let mut frame = Vec::new();
34추가: Writer::new(&mut frame, 17).send(message).unwrap();
35추가: frame
36추가: }
37추가:
38추가: fn resize_body(frame: &mut [u8]) {
39추가: let length = (frame.len() - 32) as u32;
40추가: frame[8..12].copy_from_slice(&length.to_le_bytes());
41추가: }
42추가:
43추가: fn ids_offset() -> usize {
44추가: 32 + 1 + 1 + 4 + ARCHIVE.len() + 1 + 4 + DESTINATION.len() + 1
45추가: }
46추가:
47추가: fn unchecked_frame(count: usize, kind: u16, ceiling: u32) -> Vec<u8> {
48추가: let mut frame = encoded(&request(0, kind, ceiling));
49추가: let at = ids_offset();
50추가: let mut ids = (count as u32).to_le_bytes().to_vec();
51추가: for id in 0..count as u32 {
52추가: ids.extend(id.to_le_bytes());
53추가: }
54추가: frame.splice(at..at + 4, ids);
55추가: resize_body(&mut frame);
56추가: frame
57추가: }
58추가:
59추가: fn boundary(count: usize, kind: u16, ceiling: u32, accepted: bool) {
60추가: let mut frame = Vec::new();
61추가: let result = Writer::new(&mut frame, 17).send(&request(count, kind, ceiling));
62추가: assert_eq!(result.is_ok(), accepted, "encode {kind} {ceiling} {count}");
63추가: if !accepted {
64추가: assert!(frame.is_empty());
65추가: }
66추가: let raw = unchecked_frame(count, kind, ceiling);
67추가: let result = Reader::new(raw.as_slice()).read();
68추가: assert_eq!(result.is_ok(), accepted, "decode {kind} {ceiling} {count}");
69추가: if accepted {
70추가: assert_eq!(frame, raw);
71추가: assert!(frame.len() - 32 <= MAX_BODY);
72추가: let (_, _, decoded) = result.unwrap().unwrap();
73추가: let start = match decoded {
74추가: Message::Start(start) | Message::StartInteractive(start) => start,
75추가: Message::StartGuarded(start) => start.start,
76추가: other => panic!("{other:?}"),
77추가: };
78추가: let Action::Extract {
79추가: selection: Selection::EntryIds(ids),
80추가: ..
81추가: } = start.action
82추가: else {
83추가: panic!("missing selection");
84추가: };
85추가: assert_eq!(ids.len(), count);
86추가: assert!(
87추가: ids.iter()
88추가: .enumerate()
89추가: .all(|(index, id)| *id as usize == index)
90추가: );
91추가: }
92추가: }
93추가:
94추가: #[test]
95추가: fn expanded_selection_round_trips_exact_policy_boundaries() {
96추가: for count in [32_768, 32_769, 200_000, 200_001] {
97추가: boundary(count, 6, 200_000, count <= 200_000);
98추가: }
99추가: }
100추가:
101추가: #[test]
102추가: fn legacy_and_unexpanded_requests_keep_the_original_selection_bound() {
103추가: for kind in [1, 4, 6] {
104추가: for count in [32_768, 32_769, 200_000, 200_001] {
105추가: boundary(count, kind, 10_000, count <= 32_768);
106추가: }
107추가: }
108추가: }
109추가:
110추가: #[test]
111추가: fn guarded_selection_honors_lower_ceilings_and_rejects_truncated_counts() {
112추가: boundary(40_000, 6, 40_000, true);
113추가: boundary(40_001, 6, 40_000, false);
114추가: let mut short = unchecked_frame(0, 6, 200_000);
115추가: short[ids_offset()..ids_offset() + 4].copy_from_slice(&u32::MAX.to_le_bytes());
116추가: assert!(Reader::new(short.as_slice()).read().is_err());
117추가: let mut frame = unchecked_frame(200_000, 6, 200_000);
118추가: frame.truncate(frame.len() - 1);
119추가: assert!(Reader::new(frame.as_slice()).read().is_err());
120추가: resize_body(&mut frame);
121추가: assert!(Reader::new(frame.as_slice()).read().is_err());
122추가: let mut invalid_ceiling = unchecked_frame(32_769, 6, 200_000);
123추가: let at = invalid_ceiling.len() - 5;
124추가: invalid_ceiling[at..at + 4].copy_from_slice(&200_001u32.to_le_bytes());
125추가: assert!(Reader::new(invalid_ceiling.as_slice()).read().is_err());
126추가: }
127추가:
128추가: #[test]
129추가: fn expanded_selection_does_not_expand_paths_sources_or_frame_bounds() {
130추가: for path in [
131추가: NativePath::Unix(vec![b'a'; 32_769]),
132추가: NativePath::Windows(vec![b'a' as u16; 32_769]),
133추가: ] {
134추가: let Message::StartGuarded(mut guarded) = request(0, 6, 200_000) else {
135추가: unreachable!();
136추가: };
137추가: if let Action::Extract { archive, .. } = &mut guarded.start.action {
138추가: *archive = path;
139추가: }
140추가: assert!(
141추가: Writer::new(Vec::new(), 17)
142추가: .send(&Message::StartGuarded(guarded))
143추가: .is_err()
144추가: );
145추가: }
146추가: let mut long_path = unchecked_frame(0, 6, 200_000);
147추가: let at = 32 + 1 + 1;
148추가: let mut value = 32_769u32.to_le_bytes().to_vec();
149추가: value.extend(vec![b'a'; 32_769]);
150추가: long_path.splice(at..at + 4 + ARCHIVE.len(), value);
151추가: resize_body(&mut long_path);
152추가: assert!(Reader::new(long_path.as_slice()).read().is_err());
153추가:
154추가: let source = Source {
155추가: path: NativePath::Unix(b"/s".to_vec()),
156추가: archive_name: "s".into(),
157추가: };
158추가: let create = |sources| {
159추가: Message::StartGuarded(GuardedStart {
160추가: start: Start {
161추가: action: Action::CreateZip {
162추가: sources,
163추가: output_file: NativePath::Unix(b"/new.zip".to_vec()),
164추가: method: Method::Store,
165추가: encryption: Encryption::None,
166추가: },
167추가: limits: Limits::default(),
168추가: },
169추가: ceiling: Limits {
170추가: entries: 200_000,
171추가: ..Limits::default()
172추가: },
173추가: interactive: false,
174추가: })
175추가: };
176추가: assert!(
177추가: Writer::new(Vec::new(), 17)
178추가: .send(&create(vec![source; 32_769]))
179추가: .is_err()
180추가: );
181추가: let mut sources = encoded(&create(Vec::new()));
182추가: let mut value = 32_769u32.to_le_bytes().to_vec();
183추가: for _ in 0..32_769 {
184추가: value.extend([1, 2, 0, 0, 0, b'/', b's', 1, 0, 0, 0, b's']);
185추가: }
186추가: sources.splice(33..37, value);
187추가: resize_body(&mut sources);
188추가: assert!(Reader::new(sources.as_slice()).read().is_err());
189추가:
190추가: let mut oversized = unchecked_frame(0, 6, 200_000);
191추가: oversized[8..12].copy_from_slice(&((MAX_BODY + 1) as u32).to_le_bytes());
192추가: assert!(Reader::new(oversized.as_slice()).read().is_err());
193추가: }