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
2 changes: 1 addition & 1 deletion src/OneScript.StandardLibrary/Binary/FileStreamContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace OneScript.StandardLibrary.Binary
/// Следует учитывать, что помимо буферизации существует кэширование чтения и записи файлов в операционной системе, на которое невозможно повлиять программно.
/// </summary>
[ContextClass("ФайловыйПоток", "FileStream")]
public class FileStreamContext : AutoContext<FileStreamContext>, IStreamWrapper, IDisposable
public class FileStreamContext : AutoContext<FileStreamContext>, IDisposable, IStreamWrapper
{

private readonly FileStream _underlyingStream;
Expand Down
29 changes: 27 additions & 2 deletions src/OneScript.StandardLibrary/Json/JSONReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ This Source Code Form is subject to the terms of the
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/

using System;
using System.IO;
using Newtonsoft.Json;
using OneScript.Commons;
using OneScript.Contexts;
using OneScript.Exceptions;
using OneScript.StandardLibrary.Binary;
using OneScript.StandardLibrary.Text;
using ScriptEngine.Machine;
using ScriptEngine.Machine.Contexts;
using System;
using System.IO;

namespace OneScript.StandardLibrary.Json
{
Expand Down Expand Up @@ -266,6 +267,30 @@ public void OpenFile(string JSONFileName, IValue encoding = null)
};
}

/// <summary>
/// Устанавливает поток для чтения JSON данным объектом.
/// Если перед вызовом данного метода уже производилось чтение JSON из другого файла, строки или потока,
/// то чтение прекращается и объект инициализируется для чтения из указанного потока.
/// </summary>
/// <param name="streamContext">
/// Поток для чтения текста JSON.</param>
/// <param name="encoding">
/// Позволяет задать кодировку входного потока.</param>
[ContextMethod("ОткрытьПоток", "OpenStream")]
public void OpenStream(IStreamWrapper streamContext, IValue encoding = null)
{
if (IsOpen())
Close();

var stream = streamContext.GetUnderlyingStream();
Comment on lines +280 to +285
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Add null validation for the streamContext parameter.

The method does not validate that streamContext is non-null before calling GetUnderlyingStream() on line 285. While OneScript script calls may not pass null, direct C# calls to this method could, resulting in a NullReferenceException.

🛡️ Proposed fix to add defensive null check
 public void OpenStream(IStreamWrapper streamContext, IValue encoding = null)
 {
+    if (streamContext == null)
+        throw new ArgumentNullException(nameof(streamContext));
+
     if (IsOpen())
         Close();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void OpenStream(IStreamWrapper streamContext, IValue encoding = null)
{
if (IsOpen())
Close();
var stream = streamContext.GetUnderlyingStream();
public void OpenStream(IStreamWrapper streamContext, IValue encoding = null)
{
if (streamContext == null)
throw new ArgumentNullException(nameof(streamContext));
if (IsOpen())
Close();
var stream = streamContext.GetUnderlyingStream();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 280 - 285, The
OpenStream method lacks a null check for its streamContext parameter; before
calling streamContext.GetUnderlyingStream() add a defensive validation that
throws an ArgumentNullException (or returns an appropriate error) when
streamContext is null. Locate OpenStream in JSONReader.cs and insert the null
check at the top (after the IsOpen/Close handling if desired) so the call to
GetUnderlyingStream() is only made on a non-null streamContext. Ensure the
exception message names the parameter ("streamContext") to aid callers.

var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;

_reader = new JsonReaderInternal(new StreamReader(stream, enc))
{
SupportMultipleContent = true
};
}

/// <summary>
/// Если текущее значение – начало массива или объекта, то пропускает его содержимое и конец.
/// Для остальных типов значений работает аналогично методу Прочитать().
Expand Down
12 changes: 12 additions & 0 deletions tests/json/test-json_reader.os
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
СписокТестов.Добавить("Тест_Должен_ПроверитьПропускНезавершенногоМассива");
СписокТестов.Добавить("Тест_Должен_ПроверитьПропускМассиваСВложенными");
СписокТестов.Добавить("Тест_Должен_ПроверитьПропускОбъектаСВложениями");

СписокТестов.Добавить("Тест_Должен_ПроверитьОткрытиеПотока");
Возврат СписокТестов;

КонецФункции
Expand Down Expand Up @@ -219,3 +221,13 @@
юТест.ПроверитьРавенство(ТипЗначенияJSON.Число, Чтение.ТипТекущегоЗначения);
юТест.ПроверитьРавенство(5, Чтение.ТекущееЗначение);
КонецПроцедуры

Процедура Тест_Должен_ПроверитьОткрытиеПотока() Экспорт
БДД = ПолучитьБуферДвоичныхДанныхИзСтроки("{""ответ"":42}");
Поток = Новый ПотокВПамяти(БДД);
Чтение = Новый ЧтениеJSON;
Чтение.ОткрытьПоток(Поток);
Json = ПрочитатьJSON(Чтение);

юТест.ПроверитьРавенство(42, Json.Ответ);
КонецПроцедуры